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/events.py ADDED
@@ -0,0 +1,554 @@
1
+ """Append-only evidence log: events/YYYY/MM/<session>.jsonl (docs/tools.md "Event").
2
+
3
+ Server-stamped fields never come from `fields`; reads skip torn or invalid lines.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import logging
10
+ import math
11
+ import os
12
+ import re
13
+ import threading
14
+ from collections.abc import Iterator
15
+ from datetime import UTC, datetime, timedelta, tzinfo
16
+ from pathlib import Path
17
+
18
+ from keepfold.vault import ID_RE, Vault, VaultError, check_day, invalid, scan_secrets
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ SOURCES = {"tutor", "self", "external", "imported", "run", "safety_net"}
23
+ KINDS = {"ask", "grade", "log", "taught", "void", "remap", "resume", "close", "open",
24
+ "change"}
25
+ MODES = {"home", "learn", "short", "review", "log", "about", "week", "ambient", "capture",
26
+ "reflect",
27
+ "project", "save", "history", "sweep", "mock",
28
+ "tidy", # tidy: the app's sweep of about-me lines (Keepfold.tidy), never a study mode
29
+ "harvest"} # harvest: facts from imported chats saved as guesses (fact_harvest)
30
+ STUDY_MODES = frozenset({"home", "learn", "short", "review", "log", "reflect",
31
+ "sweep"}) # not ambient
32
+
33
+ _ID = ID_RE.pattern[1:-1]
34
+ OBJECT_RE = re.compile(
35
+ rf"^(concept|problem|assessment|application|mistake|inbox|area|domain):{_ID}$")
36
+ SESSION_RE = re.compile(r"^(s_[0-9A-HJKMNP-TV-Z]{26}|cli|import)$")
37
+
38
+ SERVER_FIELDS = {"id", "key", "ts", "day", "session", "kind", "mode", "source",
39
+ "predicted_p", "grader", "schema"}
40
+ TEXT_LIMIT = 2000
41
+ TEXT_LIMITS = {"question": TEXT_LIMIT, "answer_key": TEXT_LIMIT, "learner_answer": TEXT_LIMIT,
42
+ "ref": 300,
43
+ "summary": 600}
44
+ FIELD_ENUMS = {
45
+ "item_type": {"recall", "application", "transfer"},
46
+ "verdict": {"correct", "partial", "wrong"},
47
+ "model_verdict": {"correct", "partial", "wrong"},
48
+ }
49
+ INT_RANGES = {"confidence": (1, 4), "hints": (0, 3)}
50
+ ID_LISTS = {"mistakes", "targets_mistakes"}
51
+ CLIENT_FIELDS = (set(TEXT_LIMITS) | set(FIELD_ENUMS) | set(INT_RANGES) | ID_LISTS
52
+ | {"object", "problem", "also", "payload"})
53
+ DAY_ROLLOVER = timedelta(hours=4)
54
+
55
+
56
+ def local_day(ts_utc: datetime, tz: tzinfo | None = None) -> str:
57
+ """Local date of `ts_utc`, rolling over at 04:00. `tz` defaults to the system zone."""
58
+ if ts_utc.tzinfo is None:
59
+ ts_utc = ts_utc.replace(tzinfo=UTC)
60
+ return (ts_utc.astimezone(tz) - DAY_ROLLOVER).date().isoformat()
61
+
62
+
63
+ def parse_ts(ts: str) -> datetime:
64
+ """An event's `ts` (UTC, whole seconds) as an aware datetime."""
65
+ return datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
66
+
67
+
68
+ _BIG_O = re.compile(r"o\(([^)]*)\)")
69
+
70
+
71
+ def norm_answer(s: str) -> str:
72
+ """Lowercase, no backticks or `$`, collapsed whitespace, Big-O spaces removed: the
73
+ server's answer_key match (§15a.11)."""
74
+ s = " ".join(s.lower().replace("`", "").replace("$", "").split())
75
+ return _BIG_O.sub(lambda m: "o(" + re.sub(r"\s+", "", m.group(1)) + ")", s)
76
+
77
+
78
+ def live(events) -> list[dict]:
79
+ """The non-void events whose id no void references."""
80
+ evs = list(events)
81
+ voided = {e.get("ref") for e in evs if e.get("kind") == "void"}
82
+ return [e for e in evs if e.get("kind") != "void" and e.get("id") not in voided]
83
+
84
+
85
+ def _strings(value) -> Iterator[str]:
86
+ if isinstance(value, str):
87
+ yield value
88
+ elif isinstance(value, dict):
89
+ for k, v in value.items():
90
+ yield from _strings(k)
91
+ yield from _strings(v)
92
+ elif isinstance(value, (list, tuple)):
93
+ for v in value:
94
+ yield from _strings(v)
95
+
96
+
97
+ def _check_text(name: str, value, limit: int) -> None:
98
+ if not isinstance(value, str):
99
+ raise invalid(f"{name} must be a string.")
100
+ if len(value) > limit:
101
+ raise invalid(f"{name} is {len(value)} characters; keep it to {limit} or fewer.")
102
+
103
+
104
+ def _what(event: dict) -> tuple:
105
+ """What an event records, for telling a retry from a different call with the same key."""
106
+ payload = event.get("payload")
107
+ return (event.get("kind"), event.get("object"),
108
+ payload.get("kind") if isinstance(payload, dict) else None)
109
+
110
+
111
+ def _check_fields(fields: dict) -> None:
112
+ if not isinstance(fields, dict):
113
+ raise invalid("fields must be an object.")
114
+ for name, value in fields.items():
115
+ if name in SERVER_FIELDS:
116
+ raise invalid(f"'{name}' is filled by the server; leave it out.")
117
+ if name not in CLIENT_FIELDS:
118
+ raise invalid(f"Unknown event field '{name}'; allowed: "
119
+ f"{', '.join(sorted(CLIENT_FIELDS))}.")
120
+ if name in TEXT_LIMITS:
121
+ _check_text(name, value, TEXT_LIMITS[name])
122
+ elif name in FIELD_ENUMS:
123
+ if not isinstance(value, str) or value not in FIELD_ENUMS[name]:
124
+ raise invalid(f"{name} must be one of {', '.join(sorted(FIELD_ENUMS[name]))}.")
125
+ elif name in INT_RANGES:
126
+ lo, hi = INT_RANGES[name]
127
+ if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
128
+ raise invalid(f"{name} must be a whole number from {lo} to {hi}.")
129
+ elif name in ("object", "problem"):
130
+ if not isinstance(value, str) or not OBJECT_RE.fullmatch(value):
131
+ raise invalid(f"{name} must look like concept:<id>, problem:<id> or inbox:<slug>.")
132
+ elif name == "also":
133
+ if not isinstance(value, list) or not all(
134
+ isinstance(v, str) and OBJECT_RE.fullmatch(v) for v in value):
135
+ raise invalid("also must be a list like [\"concept:<id>\"].")
136
+ elif name in ID_LISTS:
137
+ if not isinstance(value, list) or not all(
138
+ isinstance(v, str) and ID_RE.fullmatch(v) for v in value):
139
+ raise invalid(f"{name} must be a list of mistake ids.")
140
+ elif name == "payload":
141
+ if not isinstance(value, dict):
142
+ raise invalid("payload must be an object.")
143
+ try: # NaN or Infinity would write a line that is not JSON
144
+ json.dumps(value, allow_nan=False)
145
+ except (ValueError, TypeError):
146
+ raise invalid("payload values must be plain JSON (no NaN or Infinity).") \
147
+ from None
148
+ for s in _strings(value):
149
+ _check_text("A payload value", s, TEXT_LIMIT)
150
+
151
+
152
+ _TAIL = 64 # bytes before the parsed end that must still match for an incremental read
153
+
154
+
155
+ class _Parsed:
156
+ """One event file's parse, in-process only. `events` come from the newline-terminated
157
+ bytes [0, length) (`lines` lines), whose last _TAIL bytes are `tail`; `view` adds a valid
158
+ unterminated last line, if any. `key` is the (st_ino, mtime_ns, size) it was read at."""
159
+ __slots__ = ("key", "events", "length", "lines", "tail", "view")
160
+
161
+ def __init__(self):
162
+ self.key, self.events, self.length, self.lines, self.tail = None, [], 0, 0, b""
163
+ self.view = self.events
164
+
165
+
166
+ # The log is append-only, so a file that only grew (same inode, its old tail unchanged) is
167
+ # read from where the last parse ended; anything else (undo's os.replace, a truncation, a
168
+ # same-size rewrite) is parsed again whole. Bad lines are logged once, when first parsed.
169
+ _PARSED: dict[Path, _Parsed] = {}
170
+ _PARSE_LOCK = threading.Lock() # app and MCP threads would otherwise extend one _Parsed twice
171
+ # per process, not per EventLog: the app server builds one EventLog per request
172
+ _LAST_ID: int = 0
173
+ _ID_LOCK = threading.Lock()
174
+
175
+
176
+ def _stat_key(st: os.stat_result) -> tuple[int, int, int]:
177
+ return st.st_ino, st.st_mtime_ns, st.st_size
178
+
179
+
180
+ def _renamed(ev: dict) -> dict:
181
+ """Events written before the rename (Cortex 0.6.1 and older) stay as written on disk; every
182
+ fold and filter reads them here under the new names: the app's own client `cortex-app` (a
183
+ grade's grader.client, an open's payload.client) and a keyed change's tool `cortex_*`."""
184
+ for d, k in ((ev.get("grader"), "client"), (ev.get("payload"), "client")):
185
+ if isinstance(d, dict) and d.get(k) == "cortex-app":
186
+ d[k] = "keepfold-app"
187
+ p = ev.get("payload")
188
+ if isinstance(p, dict) and isinstance(t := p.get("tool"), str) and t.startswith("cortex_"):
189
+ p["tool"] = "keepfold_" + t.removeprefix("cortex_")
190
+ return ev
191
+
192
+
193
+ def _parse_lines(path: Path, data: bytes, first: int = 0, quiet: bool = False) -> list[dict]:
194
+ out = []
195
+ for n, line in enumerate(data.split(b"\n"), first + 1):
196
+ if not line.strip():
197
+ continue
198
+ try:
199
+ ev = json.loads(line.decode("utf-8"))
200
+ if not (isinstance(ev, dict) and isinstance(ev.get("ts"), str)
201
+ and isinstance(ev.get("id"), str)):
202
+ raise ValueError("not an event object")
203
+ except ValueError as e: # JSON and Unicode errors subclass ValueError
204
+ if not quiet:
205
+ log.warning("skipping %s line %d: %s", path, n, e)
206
+ continue
207
+ out.append(_renamed(ev))
208
+ return out
209
+
210
+
211
+ def _parse_file(path: Path, key: tuple[int, int, int], hit: _Parsed | None) -> _Parsed:
212
+ """`path` parsed at `key`: only the bytes past `hit` when the file just grew."""
213
+ with open(path, "rb") as f:
214
+ if hit is not None and hit.key[0] == key[0] and key[2] > hit.key[2]:
215
+ f.seek(hit.length - len(hit.tail))
216
+ data = f.read()
217
+ if data.startswith(hit.tail):
218
+ return _extend(path, key, hit, data, len(hit.tail))
219
+ f.seek(0)
220
+ return _extend(path, key, _Parsed(), f.read(), 0)
221
+
222
+
223
+ def _extend(path: Path, key, p: _Parsed, data: bytes, skip: int) -> _Parsed:
224
+ """Add to `p` the lines of `data[skip:]`, which starts at file offset p.length; `data[:skip]`
225
+ is p.tail. An unterminated last line goes only to `view`, silently: it may be mid-write, and
226
+ it is parsed (and logged if bad) once a newline completes it."""
227
+ end = max(data.rfind(b"\n") + 1, skip)
228
+ if end > skip:
229
+ done = data[skip:end]
230
+ p.events.extend(_parse_lines(path, done, p.lines))
231
+ p.lines += done.count(b"\n")
232
+ p.length += end - skip
233
+ p.tail = data[max(0, end - _TAIL):end]
234
+ rest = data[end:]
235
+ pending = _parse_lines(path, rest, p.lines, quiet=True) if rest.strip() else []
236
+ p.view = p.events + pending if pending else p.events
237
+ p.key = key
238
+ return p
239
+
240
+
241
+ _WARNED: set[Path] = set() # conflict copies already warned about: once per file
242
+
243
+
244
+ def _merged(files: list[tuple[Path, _Parsed]], session: str | None = None) -> list[dict]:
245
+ """The events of `files`, each id once. A file not named <session>.jsonl is a sync tool's
246
+ conflict copy (Syncthing, OneDrive, Dropbox: `keepfold doctor` names them): it adds only the
247
+ ids the session files lack (the other device's appends) and, when `session` is given, only
248
+ that session's events. An id held with other content keeps the session file's (a copy's,
249
+ between copies, the first by path), with one warning per copy."""
250
+ own = [SESSION_RE.fullmatch(path.stem) is not None for path, _ in files]
251
+ if all(own): # no copies: nothing to merge
252
+ return [ev for _, p in files for ev in p.view]
253
+ seen: dict[str, dict] = {}
254
+ out = []
255
+ # session files first (a stable sort: path order within each)
256
+ for mine, (path, p) in sorted(zip(own, files, strict=True), key=lambda f: not f[0]):
257
+ for ev in p.view:
258
+ if not mine and session is not None and ev.get("session") != session:
259
+ continue
260
+ first = seen.setdefault(ev["id"], ev)
261
+ if first is ev:
262
+ out.append(ev)
263
+ elif first != ev and not mine and path not in _WARNED:
264
+ _WARNED.add(path)
265
+ log.warning("%s (a sync conflict copy) holds events that differ from another "
266
+ "file's with the same id; the session file's are kept", path)
267
+ return out
268
+
269
+
270
+ class EventLog:
271
+ def __init__(self, vault: Vault):
272
+ self.vault = vault
273
+ self._keys: dict[str, dict] = {}
274
+ self._sig: dict[Path, tuple] | None = None # the file keys self._keys was built from
275
+
276
+ # ---- reading ------------------------------------------------------------
277
+
278
+ def _dir(self):
279
+ return self.vault.root / "events"
280
+
281
+ def iter_events(self, session: str | None = None) -> Iterator[dict]:
282
+ """All events (or one session's), sorted by (ts, id). Bad lines are logged and skipped."""
283
+ if session is not None and not SESSION_RE.fullmatch(session):
284
+ raise invalid("session must be s_<ULID>, cli or import.")
285
+ # `<session>*`: its sync conflict copies too (`_merged` keeps only this session's events)
286
+ pattern = f"*/*/{session}*.jsonl" if session else "*/*/*.jsonl"
287
+ # shortcut: shallow copies guard top-level edits only; nested dicts are shared and
288
+ # no caller mutates them. Deep-copy here if one ever must.
289
+ out = [dict(ev) for ev in self._cached(pattern, session)]
290
+ out.sort(key=lambda e: (e["ts"], e["id"]))
291
+ return iter(out)
292
+
293
+ def signature(self) -> tuple:
294
+ """Every event file with its (ino, mtime_ns, size): while it is equal, so is
295
+ iter_events(). Statting the files reads (and caches) any that changed."""
296
+ return tuple((path, p.key) for path, p in self._files("*/*/*.jsonl"))
297
+
298
+ def _files(self, pattern: str) -> list[tuple[Path, _Parsed]]:
299
+ """The up-to-date parses of the files matching `pattern`."""
300
+ out = []
301
+ for path in sorted(self._dir().glob(pattern)):
302
+ try:
303
+ with _PARSE_LOCK:
304
+ key = _stat_key(path.stat()) # before the read: a later change shows next time
305
+ hit = _PARSED.get(path)
306
+ if hit is None or hit.key != key:
307
+ hit = _PARSED[path] = _parse_file(path, key, hit)
308
+ except OSError as e:
309
+ log.warning("skipping %s: %s", path, e)
310
+ continue
311
+ out.append((path, hit))
312
+ return out
313
+
314
+ def _cached(self, pattern: str, session: str | None = None) -> list[dict]:
315
+ """The parse-cached events of the files matching `pattern`, each id once (`_merged`),
316
+ unsorted and shared with the cache: callers must not mutate them."""
317
+ return _merged(self._files(pattern), session)
318
+
319
+ def _key_map(self) -> dict[str, dict]:
320
+ """key -> its first event (by ts, id), shared with the cache. Rebuilt whenever any file
321
+ changed other than by this instance's own append (which updates it in place): another
322
+ process's keys and a file reverted by keepfold undo must both be seen."""
323
+ files = self._files("*/*/*.jsonl")
324
+ sig = {path: p.key for path, p in files}
325
+ if sig != self._sig:
326
+ self._keys = {}
327
+ for ev in _merged(files):
328
+ self._add_key(ev)
329
+ self._sig = sig
330
+ return self._keys
331
+
332
+ def _add_key(self, ev: dict) -> None:
333
+ k, keys = ev.get("key"), self._keys
334
+ if isinstance(k, str) and (k not in keys or (ev["ts"], ev["id"]) < (
335
+ keys[k]["ts"], keys[k]["id"])):
336
+ keys[k] = ev
337
+
338
+ def has_key(self, key) -> bool:
339
+ return key in self._key_map()
340
+
341
+ # ---- writing ------------------------------------------------------------
342
+
343
+ def _new_id(self, now: datetime) -> str:
344
+ from ulid import ULID # lazy: its import costs ~0.3 s, and readers (prime-hook) never mint
345
+
346
+ global _LAST_ID
347
+ new = ULID.from_datetime(now)
348
+ with _ID_LOCK:
349
+ if int(new) <= _LAST_ID:
350
+ new = ULID.from_int(_LAST_ID + 1) # keep ids monotonic in this process
351
+ _LAST_ID = int(new)
352
+ return str(new)
353
+
354
+ def append(self, *, session: str, kind: str, source: str, fields: dict,
355
+ mode: str | None = None, key: str | None = None,
356
+ predicted_p: float | None = None, grader: dict | None = None,
357
+ now: datetime | None = None) -> dict:
358
+ if not isinstance(session, str) or not SESSION_RE.fullmatch(session):
359
+ raise invalid("session must be s_<ULID>, cli or import.")
360
+ if kind not in KINDS:
361
+ raise invalid(f"kind must be one of {', '.join(sorted(KINDS))}.")
362
+ if source not in SOURCES:
363
+ raise invalid(f"source must be one of {', '.join(sorted(SOURCES))}.")
364
+ if mode is not None and mode not in MODES:
365
+ raise invalid(f"mode must be one of {', '.join(sorted(MODES))}.")
366
+ if key is not None:
367
+ _check_text("key", key, 300)
368
+ if predicted_p is not None and (isinstance(predicted_p, bool) or not isinstance(
369
+ predicted_p, (int, float)) or not 0 <= predicted_p <= 1):
370
+ raise invalid("predicted_p must be a number from 0 to 1.")
371
+ if grader is not None:
372
+ if not isinstance(grader, dict) or not set(grader) <= {"client", "model"}:
373
+ raise invalid("grader may hold only client and model.")
374
+ for name, value in grader.items():
375
+ if value is not None:
376
+ _check_text(f"grader.{name}", value, 300)
377
+ _check_fields(fields)
378
+ for s in _strings([fields, grader, key]):
379
+ scan_secrets(s)
380
+
381
+ now = now or datetime.now(UTC)
382
+ now = now.replace(tzinfo=UTC) if now.tzinfo is None else now.astimezone(UTC)
383
+ with self.vault.lock():
384
+ keys = self._key_map()
385
+ if key is not None and key in keys:
386
+ old = keys[key]
387
+ if _what(old) != _what({"kind": kind, **fields}): # a retry repeats the call
388
+ raise invalid("This key is already used by a different call; use a new "
389
+ "key (or none).")
390
+ return dict(old) # a copy: the cached event is shared
391
+ eid = self._new_id(now)
392
+ event = {"id": eid, "key": eid if key is None else key,
393
+ "ts": now.strftime("%Y-%m-%dT%H:%M:%SZ"), "day": local_day(now),
394
+ "session": session, "kind": kind}
395
+ if mode is not None:
396
+ event["mode"] = mode
397
+ event["source"] = source
398
+ event.update(fields)
399
+ if predicted_p is not None:
400
+ event["predicted_p"] = float(predicted_p)
401
+ if grader is not None:
402
+ event["grader"] = grader
403
+ event["schema"] = 1
404
+ self._write(event)
405
+ return event
406
+
407
+ def _write(self, event: dict) -> None:
408
+ year, month = event["day"][:4], event["day"][5:7]
409
+ path = self._dir() / year / month / f"{event['session']}.jsonl"
410
+ path.parent.mkdir(parents=True, exist_ok=True)
411
+ line = (json.dumps(event, ensure_ascii=False, separators=(",", ":")) + "\n").encode()
412
+ try:
413
+ before = _stat_key(path.stat())
414
+ except FileNotFoundError:
415
+ before = None
416
+ with open(path, "ab+") as f:
417
+ size = f.seek(0, os.SEEK_END)
418
+ if size:
419
+ f.seek(size - 1)
420
+ if f.read(1) != b"\n":
421
+ # never truncate: the line may be a whole event; a torn one is skipped on read
422
+ log.warning("closing an unterminated last line in %s", path)
423
+ f.write(b"\n")
424
+ f.write(line)
425
+ f.flush()
426
+ os.fsync(f.fileno())
427
+ self.vault._track(path)
428
+ self._remember(path, before, size, line)
429
+
430
+ def _remember(self, path: Path, before, size: int, line: bytes) -> None:
431
+ """Fold our own append into the parse cache, and the key map, so the next call reads
432
+ nothing back. Only when the cache held the whole file just before the write; otherwise
433
+ the next read catches up from the file."""
434
+ with _PARSE_LOCK: # the whole body, so a reader cannot extend the same hit meanwhile
435
+ hit = _PARSED.get(path)
436
+ if before is None and size == 0:
437
+ hit = _Parsed()
438
+ elif hit is None or hit.key != before or hit.length != size:
439
+ return
440
+ try:
441
+ after = _stat_key(path.stat())
442
+ except OSError:
443
+ _PARSED.pop(path, None)
444
+ return
445
+ ev = json.loads(line) # a copy of the returned event, exactly as a re-read gives it
446
+ hit.events.append(ev)
447
+ hit.lines += 1
448
+ hit.length += len(line)
449
+ hit.tail = (hit.tail + line)[-_TAIL:]
450
+ hit.key = after
451
+ _PARSED[path] = hit
452
+ if self._sig is not None and self._sig.get(path) == before:
453
+ self._sig[path] = after
454
+ self._add_key(ev)
455
+
456
+
457
+ def check_assessment_result(score, day) -> None:
458
+ if score is not None and (isinstance(score, bool) or not isinstance(score, (str, int, float))
459
+ or (isinstance(score, float) and not math.isfinite(score))):
460
+ raise invalid("score must be a string or a number.")
461
+ if day is not None:
462
+ check_day("date", day)
463
+
464
+
465
+ def log_assessment(log: EventLog, *, session: str, source: str, assessment: str, outcome: str,
466
+ score=None, company: str | None = None, kind: str | None = None,
467
+ date: str | None = None, felt_weak: list[str] | None = None,
468
+ key: str | None = None, **stamp) -> dict:
469
+ """assessment_result (§15a.5): create the note if missing, set outcome/score, log the event.
470
+
471
+ `stamp` (mode, grader, now) passes through to EventLog.append.
472
+ """
473
+ check_assessment_result(score, date) # B10: before the note exists
474
+ if company is not None and not isinstance(company, str):
475
+ raise invalid("company must be text.")
476
+ payload = {"kind": "assessment_result", "assessment": assessment, "outcome": outcome}
477
+ for name, value in (("score", score), ("company", company), ("assessment_kind", kind),
478
+ ("date", date), ("felt_weak", felt_weak)):
479
+ if value not in (None, "", []):
480
+ payload[name] = value
481
+ fields = {"object": f"assessment:{assessment}", "payload": payload}
482
+ _check_fields(fields) # too long or odd values are refused before anything is written
483
+ vault = log.vault
484
+ try:
485
+ vault.read("assessment", assessment)
486
+ except VaultError as e:
487
+ if e.code != "unknown_id":
488
+ raise
489
+ props = {k: v for k, v in (("company", company), ("kind", kind), ("date", date))
490
+ if v is not None}
491
+ title = " ".join(filter(None, (company, (kind or "").upper()))) or assessment
492
+ vault.create_note("assessment", assessment, {**props, "outcome": outcome},
493
+ f"# {title}\n\n## Notes\n")
494
+ vault.set_field("assessment", assessment, "outcome", outcome)
495
+ if score is not None:
496
+ vault.set_field("assessment", assessment, "score", score)
497
+ return log.append(session=session, kind="log", source=source, key=key, fields=fields,
498
+ **stamp)
499
+
500
+
501
+ def void_event(log: EventLog, *, session: str, event_id: str, reason: str, source: str,
502
+ **stamp) -> tuple[dict, dict]:
503
+ """Append a `void` for `event_id` (must exist, not be a void, not be voided already).
504
+ Returns (void event, target event); `stamp` (mode, grader, now) goes to EventLog.append."""
505
+ if not isinstance(reason, str) or not reason.strip():
506
+ raise invalid("reason is required.")
507
+ with log.vault.lock(): # B11: two voids of one event must not both pass the check
508
+ events = list(log.iter_events())
509
+ target = next((e for e in events if e["id"] == event_id), None)
510
+ if target is None:
511
+ raise VaultError("unknown_id", f"No event '{event_id}' in the log.")
512
+ if target.get("kind") == "void":
513
+ raise invalid("A void cannot be voided.")
514
+ if any(e.get("kind") == "void" and e.get("ref") == event_id for e in events):
515
+ raise invalid(f"Event '{event_id}' is already voided.")
516
+ ev = log.append(session=session, kind="void", source=source, **stamp,
517
+ fields={"ref": event_id, "payload": {"reason": reason.strip()}})
518
+ _restore_note(log, target)
519
+ return ev, target
520
+
521
+
522
+ # payload kind -> (note kind, payload id key, note field, default when no live event is left)
523
+ _RESTORE = {"problem_status": ("problem", "problem", "status", "todo"),
524
+ "assessment_result": ("assessment", "assessment", "outcome", "pending")}
525
+
526
+
527
+ def _restore_note(log: EventLog, target: dict) -> None:
528
+ """After a void, reset the field the voided event set, from the latest live event of the same
529
+ kind, unless the note no longer holds the voided value (a later hand edit is kept). An
530
+ assessment's score goes the same way: the latest live score, or no score at all."""
531
+ pl = target.get("payload")
532
+ spec = _RESTORE.get(pl.get("kind")) if isinstance(pl, dict) else None
533
+ if spec is None:
534
+ return
535
+ nkind, idkey, field, default = spec
536
+ nid = pl.get(idkey)
537
+ try:
538
+ note = log.vault.read(nkind, nid)
539
+ except VaultError:
540
+ return
541
+ mine = [e for e in live(log.iter_events()) if isinstance(e.get("payload"), dict)
542
+ and e["payload"].get("kind") == pl["kind"] and e["payload"].get(idkey) == nid]
543
+ values = {}
544
+ if note.fields.get(field) == pl.get(field):
545
+ latest = mine[-1] if mine else None
546
+ values[field] = latest["payload"][field] if latest else default
547
+ if nkind == "problem":
548
+ values["solved_on"] = latest["day"] if values[field] == "solved" else None
549
+ if "score" in pl and note.fields.get("score") == pl["score"]:
550
+ # log_assessment writes a score only when given, so the note holds the last one given
551
+ values["score"] = next((e["payload"]["score"] for e in reversed(mine)
552
+ if "score" in e["payload"]), None)
553
+ if values:
554
+ log.vault._edit_fields(nkind, nid, values)
@@ -0,0 +1,109 @@
1
+ """`keepfold export context` (v6 agenda 7): the prime core as a plain Markdown snapshot that the
2
+ user can paste into other assistants (Gemini, Codex, Cursor). It reuses prime's selection
3
+ (keepfold.prime) with as_me's act-grade rule: only live claims of tier typed or confirmed and not
4
+ labelled (ask), so never `## Past`, `## Not me`, inbox proposals, agent or exposed lines, or a
5
+ yes the model relayed from claims.RELAYED_FROM; lines carry no label. Profile is me/profile's
6
+ `summary:` field, else its act-grade claim lines. Private me/ pages and any line matching a
7
+ secret pattern are left out, as is a line review.unsafe_lines flags (G6) and a profile summary
8
+ claims.unsafe flags. It writes nothing in the vault.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+
16
+ from keepfold import claims, prime, render, review, taint
17
+ from keepfold.events import local_day
18
+ from keepfold.vault import Vault, VaultError, is_private, secret_pattern
19
+
20
+ MAX_CHARS = 6000
21
+ LINE_MAX = 300
22
+ REPO = Path(__file__).resolve().parents[2] # the Keepfold code checkout (src/keepfold/..)
23
+ HEADER = ("# About me (Keepfold snapshot, {day})\n\n"
24
+ "Exported from my Keepfold vault on {day}; it does not update. It holds only lines I "
25
+ "confirmed.")
26
+
27
+
28
+ def _clean(text: str, limit: int = LINE_MAX) -> str:
29
+ """One plain line (no links, images, URLs, HTML or `(confirmed …)` markers), or "" when it
30
+ looks like it holds a secret."""
31
+ if secret_pattern(text):
32
+ return ""
33
+ s = render.plain(claims._MARK.sub("", text), limit)
34
+ return "" if secret_pattern(s) else s
35
+
36
+
37
+ def _page_ok(vault: Vault, page: str) -> bool:
38
+ note = prime.me(vault, page)
39
+ return note is not None and not is_private(note)
40
+
41
+
42
+ def build(vault: Vault, events: list[dict], now: datetime) -> tuple[str, int]:
43
+ """(the Markdown snapshot within MAX_CHARS, how many live claim lines were left out as not
44
+ act-grade)."""
45
+ served = prime.served_claims(vault, events)
46
+ keeps = {"preferences": lambda h: True, "setup": lambda h: True,
47
+ "personality": lambda h: h in prime.PERSONALITY_HEADINGS["all"],
48
+ "goals": lambda h: h == "now", "profile": lambda h: True}
49
+ rows: dict[str, list] = {"preferences": [], "goals": [], "profile": []}
50
+ skipped = 0
51
+ unsafe = {(x["page"], x["id"]) for x in review.unsafe_lines(vault, events)} # G6
52
+ for i, r in enumerate(claims.tiers(vault, events)): # live claims only
53
+ keep = keeps.get(r["page"])
54
+ if (keep is None or not keep(r["section"].lower()) or not _page_ok(vault, r["page"])
55
+ or (r["page"], r["id"]) in unsafe
56
+ or claims.expired(r["text"], local_day(now))): # agenda 4
57
+ continue
58
+ label, score = served.get((r["page"], r["section"], r["text"]), ("", 0.5))
59
+ if not claims.act_grade(r, label):
60
+ skipped += 1
61
+ continue
62
+ if (text := _clean(r["text"])) and r["page"] == "profile":
63
+ rows["profile"].append(f"- {text}") # page order
64
+ elif text:
65
+ line = (f"- {text}" if r["page"] == "goals"
66
+ else f"- [{render.plain(r['section'], 60)}] {text}")
67
+ rows["goals" if r["page"] == "goals" else "preferences"].append((-score, -i, line))
68
+ sections = []
69
+ if _page_ok(vault, "profile"): # its summary: field, else its act-grade claim lines only
70
+ summary = str(prime.me(vault, "profile").fields.get("summary") or "")
71
+ summary = "" if summary.strip() == prime.PROFILE_TEMPLATE else summary # no fact in it
72
+ summary = "" if claims.expired(summary, local_day(now)) or claims.unsafe( # G6
73
+ summary, "profile") else _clean(claims._ANY_ID.sub("", summary), 600)
74
+ sections.append(("Profile", [summary] if summary else rows["profile"]))
75
+ if _page_ok(vault, "teaching-contract"):
76
+ rules = [s for s in map(_clean, prime.contract_core(prime.contract(vault, set()))) if s]
77
+ sections.append(("How to help me", rules))
78
+ sections.append(("Current goals", [x[-1] for x in sorted(rows["goals"])]))
79
+ sections.append(("Preferences", [x[-1] for x in sorted(rows["preferences"])]))
80
+ return _fit(HEADER.format(day=local_day(now)), sections), skipped
81
+
82
+
83
+ def _fit(header: str, sections: list[tuple[str, list[str]]]) -> str:
84
+ """Header plus non-empty sections, dropping whole lines from the end (the weakest
85
+ preferences first) until the text is within MAX_CHARS."""
86
+ secs = [(h, list(ls)) for h, ls in sections if ls]
87
+
88
+ def text() -> str:
89
+ return "\n\n".join([header, *(f"## {h}\n" + "\n".join(ls) for h, ls in secs)]) + "\n"
90
+
91
+ while secs and len(text()) > MAX_CHARS:
92
+ secs[-1][1].pop()
93
+ if not secs[-1][1]:
94
+ secs.pop()
95
+ return text()
96
+
97
+
98
+ def check_target(path: Path, vault: Vault) -> Path:
99
+ """The resolved output path; refused inside the vault, the Keepfold repo or an `exclude:`
100
+ folder, since the file holds the user's profile."""
101
+ p = path.expanduser().resolve()
102
+ for root, what in ((vault.root.resolve(), "the vault"), (REPO, "the Keepfold repo")):
103
+ if p == root or root in p.parents:
104
+ raise VaultError("invalid_argument", f"Refusing to write inside {what}; pick a "
105
+ "path outside it, or omit it to print to stdout.")
106
+ if folder := taint.excluded(p.parent):
107
+ raise VaultError("invalid_argument", f"{folder} is excluded in ~/.keepfold/config.yaml; "
108
+ "refusing to write your profile there.")
109
+ return p