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/session.py ADDED
@@ -0,0 +1,764 @@
1
+ """Session lifecycle (SPEC §0 U4, §6, §15a.6-7, §15a.9): implicit sessions, modes, idle close,
2
+ end pipeline.
3
+
4
+ Pure Python; the MCP server and the CLI drive it. Closing runs the end pipeline: `close`
5
+ event, tool props of touched concepts, then (unless the session is quiet) journal line, session
6
+ note, Today.md and log.md line, then the session's git commit. No close rebuilds a whole-vault
7
+ view: `keepfold dashboard` rewrites index.md, and the app's live home is the dashboard.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from dataclasses import dataclass, field
19
+ from datetime import UTC, datetime, timedelta
20
+ from pathlib import Path
21
+
22
+ from ulid import ULID
23
+
24
+ from keepfold import levels, planner, relink, render
25
+ from keepfold._proc import NO_WINDOW
26
+ from keepfold.catalog import Catalog
27
+ from keepfold.events import MODES, SESSION_RE, EventLog, local_day, parse_ts
28
+ from keepfold.taint import MARKER as TAINT_MARKER
29
+ from keepfold.vault import (
30
+ CHAT_ARCHIVE,
31
+ Vault,
32
+ VaultError,
33
+ _pid_alive,
34
+ is_private,
35
+ secret_pattern,
36
+ )
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+ # SPEC §0 U4: reads never need or open a session; the first write with none opens "ambient".
41
+ # Permission names: resurface, lint, split, void and quiz_result are actions of find, reflect,
42
+ # log and grade (mcp_server._action) that keep the rights of the tools they replaced.
43
+ READS = frozenset({"find", "read", "context", "lint", "reflect", "chats",
44
+ "resurface", "recall", "as_me", "prime"}) # as_me (PHASE4 V3) logs access
45
+ WRITES = frozenset({"ask", "grade", "quiz_result", "log", "patch", "add", "void", "split"})
46
+ _ALL = READS | WRITES | {"start", "end"}
47
+ _READ_ONLY = READS | {"start", "end"}
48
+ # docs/tools.md "Mode permissions". Review's ban on adding concepts/areas/domains depends on the
49
+ # add kind, so the MCP layer checks that; here review allows `add`.
50
+ ALLOWED = {
51
+ "home": _ALL, "learn": _ALL, "short": _ALL, "review": _ALL,
52
+ "log": _READ_ONLY | {"log", "patch", "add", "split"},
53
+ "about": _READ_ONLY, "week": _READ_ONLY, "ambient": _ALL,
54
+ "capture": _ALL, "reflect": _ALL, "project": _ALL, "save": _ALL, "history": _ALL,
55
+ "sweep": _ALL, "mock": _ALL, "tidy": _ALL, "harvest": _ALL,
56
+ }
57
+ IDLE_CLOSE = timedelta(hours=2)
58
+ LIVE_CLOSE = timedelta(hours=24) # B2: a sweep closes a live server's session only this idle
59
+ RESUME_AFTER = timedelta(minutes=15)
60
+ EVENT_BUDGET, PATCH_BUDGET = 40, 10
61
+ COUNT_KINDS = ("asked", "graded", "logged", "patched", "added")
62
+ # Ledger `log` kinds: they record that a chat happened (a topic touch, a resurface,
63
+ # an act-as-me read), never learning evidence, a change, a note or a grade. A session whose only
64
+ # writes are these closes quietly: its close event and commit, no journal, session note,
65
+ # Today.md or log.md line (v6 CONSENSUS item 5, r1-user P1). Every other log kind is loud.
66
+ LEDGER_LOG_KINDS = frozenset({"touch", "resurfaced", "access", "chat_learned"})
67
+ SUMMARY_MAX = 600
68
+
69
+
70
+ @dataclass
71
+ class Session:
72
+ id: str
73
+ mode: str
74
+ topic: str | None
75
+ model: str | None
76
+ started: datetime
77
+ last_activity: datetime
78
+ counts: dict[str, int] = field(default_factory=lambda: dict.fromkeys(COUNT_KINDS, 0))
79
+ ledger: int = 0 # how many of counts["logged"] were LEDGER_LOG_KINDS
80
+ touched: set[str] = field(default_factory=set)
81
+ over_events: bool = False # write budget flags: set when exceeded, never block
82
+ over_patches: bool = False
83
+ changes: list[dict] = field(default_factory=list) # {tool, id, kind, op, target} per write
84
+ before: dict = field(default_factory=dict, repr=False) # levels snapshot at start
85
+ exposed: bool = False # v5 F3: served external text; its claim writes are tier `exposed`
86
+ mark: int = 0 # vault.writes at start: files written after it are this session's to commit
87
+
88
+
89
+ def _utc(t: datetime) -> datetime:
90
+ return t.astimezone(UTC) # a naive clock value is local time
91
+
92
+
93
+ def _no_session() -> VaultError:
94
+ return VaultError("no_session", "No open Keepfold session to close.")
95
+
96
+
97
+ class SessionManager:
98
+ def __init__(self, vault: Vault, *, client: str | None = None, clock=datetime.now):
99
+ self.vault, self.client, self.clock = vault, client, clock
100
+ self.log = EventLog(vault) # share this one so idempotency keys stay cached
101
+ self.current: Session | None = None
102
+ # v6 T2: the latest outside read. Exposure follows time, not the session: any session
103
+ # opening within IDLE_CLOSE of it starts exposed, so closing one never launders it.
104
+ # shortcut: in memory only, so a server restart forgets a Keepfold-side read (a hook
105
+ # marker still counts); persist it if restarts inside a chat turn out to matter.
106
+ self._exposed_at: datetime | None = None
107
+ self._taint_since = self._now() # a taint marker older than this belongs to no chat here
108
+ # Imported chat ids a harvest bundle served and the session that served them: the
109
+ # harvest guards (`harvesting`) hold only while that session is current, and a new or
110
+ # closed session clears them. shortcut: process state, so a server restart lifts the
111
+ # guards (harvest verdict, contradiction 3); persist it if that bites.
112
+ self.served: set[str] = set()
113
+ self.served_sid: str | None = None
114
+ # R3-4: fields the Keepfold app's Review click adds to each change it writes ({card}),
115
+ # set by app/server.py around one click; never tool input
116
+ self.stamp: dict = {}
117
+
118
+ def serve(self, ids) -> None:
119
+ """A harvest bundle's chat ids, served in the current session (which must be open)."""
120
+ self.served.update(ids)
121
+ self.served_sid = self.current.id
122
+
123
+ @property
124
+ def harvesting(self) -> bool:
125
+ """True while the session that served a harvest bundle is current and not idle-closed
126
+ (the guards run before `require` would close an idle one)."""
127
+ s = self.current
128
+ return (bool(self.served) and s is not None and s.id == self.served_sid
129
+ and self._now() - s.last_activity <= IDLE_CLOSE)
130
+
131
+ def _now(self) -> datetime:
132
+ return _utc(self.clock())
133
+
134
+ def expose(self, at: datetime | None = None) -> None:
135
+ """v5 F3: external text was served (at `at`, default now). It marks the open session
136
+ and every session that opens within IDLE_CLOSE after it."""
137
+ at = at or self._now()
138
+ self._exposed_at = max(self._exposed_at or at, at)
139
+ if self.current is not None:
140
+ self.current.exposed = True
141
+
142
+ def _check_taint(self) -> None:
143
+ """Hook exposure: `keepfold taint` (the plugin's PostToolUse hook) touches the marker when
144
+ Claude reads outside text with a non-Keepfold tool. A marker newer than this server's
145
+ start and under 2 h old exposes like a Keepfold read."""
146
+ if self.current is not None and self.current.exposed:
147
+ return
148
+ try:
149
+ mtime = (self.vault.root / TAINT_MARKER).stat().st_mtime
150
+ except OSError:
151
+ return
152
+ # shortcut: one marker per vault, so a web read in any concurrent Claude Code chat
153
+ # exposes this server's session too (the safe direction); key it by chat if that bites.
154
+ t = datetime.fromtimestamp(mtime, UTC)
155
+ if t > self._taint_since and self._now() - t < IDLE_CLOSE:
156
+ self.expose(t)
157
+
158
+ def start(self, mode: str = "learn", topic: str | None = None,
159
+ model: str | None = None) -> Session:
160
+ if mode not in MODES:
161
+ raise VaultError("invalid_argument", f"mode must be one of {', '.join(sorted(MODES))}.")
162
+ if self.current is not None:
163
+ self.close(summary="auto-closed: new session started")
164
+ self.served.clear() # a new session is never a harvest in progress
165
+ now = self._now()
166
+ before, _ = planner.current_states(self.vault, local_day(now))
167
+ recent = self._exposed_at is not None and now - self._exposed_at < IDLE_CLOSE
168
+ self.current = Session(id=f"s_{ULID.from_datetime(now)}", mode=mode, topic=topic,
169
+ model=model, started=now, last_activity=now, before=before,
170
+ mark=self.vault.writes, exposed=mode == "capture" or recent)
171
+ # an event so a sweep can find (and close and commit) a session that wrote no others;
172
+ # the pid lets a sweep close it as soon as this server process has gone; `client` (the
173
+ # MCP handshake's name, never tool input) names the AI app for the app's Tonight tab
174
+ self.log.append(session=self.current.id, kind="open", source="tutor", mode=mode,
175
+ fields={"payload": {"pid": os.getpid(), **(
176
+ {"client": self.client[:100]} if self.client else {})}}, now=now)
177
+ return self.current
178
+
179
+ def require(self, tool: str, label: str | None = None) -> Session | None:
180
+ """The open session for `tool`. With none (or after an idle close), a read gets None
181
+ and a write opens an ambient session; anything else is `no_session`. `label` names
182
+ the call in the refusal message."""
183
+ s = self.current
184
+ now = self._now()
185
+ if s is not None and now - s.last_activity > IDLE_CLOSE:
186
+ # B15: it ended at its last activity (+1 s: the close sorts after its last event)
187
+ self.close(summary="auto-closed after 2 h idle",
188
+ ended=s.last_activity + timedelta(seconds=1))
189
+ s = None
190
+ self._check_taint()
191
+ if s is not None and tool in WRITES and any(
192
+ e.get("kind") == "close" for e in self.log.iter_events(session=s.id)):
193
+ # B2: another process closed it (a sweep, `keepfold session close`); a write there
194
+ # would miss its commit and `keepfold undo`, so it goes to a fresh session
195
+ self._closed()
196
+ new = self.start(s.mode, s.topic, s.model)
197
+ new.exposed = new.exposed or s.exposed # a reopen never launders exposure
198
+ s = new
199
+ if s is None:
200
+ if tool in READS:
201
+ return None
202
+ if tool in WRITES:
203
+ return self.start("ambient")
204
+ raise _no_session()
205
+ idle = now - s.last_activity
206
+ if idle > RESUME_AFTER:
207
+ self.log.append(session=s.id, kind="resume", source="tutor", mode=s.mode,
208
+ fields={}, now=now)
209
+ if tool not in ALLOWED[s.mode]:
210
+ raise VaultError("read_only_mode", f"{label or 'keepfold_' + tool} is not available "
211
+ f"in {s.mode} mode; call keepfold_end first, then retry.")
212
+ s.last_activity = now
213
+ return s
214
+
215
+ def note(self, kind: str, concept: str | None = None, change: dict | None = None, *,
216
+ log_kind: str | None = None) -> str:
217
+ """Count a write; `change` is its record for the end card; `log_kind` is a logged
218
+ write's keepfold_log kind. Returns a soft hint the call that first pushes patches/adds
219
+ over budget appends to its `next`, else ""."""
220
+ s = self.current
221
+ if s is None:
222
+ raise _no_session()
223
+ if kind not in (*COUNT_KINDS, "voided", "journal"):
224
+ raise ValueError(f"kind must be one of {COUNT_KINDS}")
225
+ if kind in COUNT_KINDS:
226
+ s.counts[kind] += 1
227
+ if kind == "logged" and log_kind in LEDGER_LOG_KINDS:
228
+ s.ledger += 1
229
+ if concept:
230
+ s.touched.add(concept)
231
+ if change:
232
+ change = {**change, **self.stamp}
233
+ s.changes.append(change)
234
+ if change or kind in ("patched", "added"):
235
+ self._persist(s, kind, concept, change)
236
+ c = s.counts
237
+ events = c["asked"] + c["graded"] + c["logged"]
238
+ crossed_ev = not s.over_events and events > EVENT_BUDGET
239
+ s.over_events = s.over_events or crossed_ev
240
+ writes = c["patched"] + c["added"]
241
+ crossed = not s.over_patches and writes > PATCH_BUDGET
242
+ s.over_patches = s.over_patches or crossed
243
+ wrap = "; consider wrapping up with keepfold_end."
244
+ return ((f" This session has made {writes} changes{wrap}" if crossed else "")
245
+ + (f" This session has recorded {events} events{wrap}" if crossed_ev else ""))
246
+
247
+ def _persist(self, s: Session, kind: str, concept: str | None, change: dict | None) -> None:
248
+ """A `change` event so a sweep-close rebuilds the counts and Changed list (levels and
249
+ the planner ignore it). It must never fail the write it records. `exposed` (v6 T3) is
250
+ stamped from the session, never from tool input."""
251
+ payload = {"note": kind, **({"concept": concept} if concept else {}),
252
+ **({"change": change} if change else {}),
253
+ **({"exposed": True} if s.exposed else {})}
254
+ try:
255
+ self.log.append(session=s.id, kind="change", source="tutor", mode=s.mode,
256
+ fields={"payload": payload}, now=self._now())
257
+ except VaultError as e:
258
+ log.warning("change event not recorded: %s", e)
259
+
260
+ def close(self, summary: str = "", ended: datetime | None = None) -> dict:
261
+ """`ended`: when the session really ended (an idle close: its last activity)."""
262
+ s = self.current
263
+ if s is None:
264
+ raise _no_session()
265
+ return _end(self.vault, self.log, sid=s.id, mode=s.mode, started=s.started,
266
+ ended=ended or self._now(), now=self._now(), counts=s.counts,
267
+ touched=s.touched, before=s.before,
268
+ summary=summary, changes=s.changes, mark=s.mark, ledger=s.ledger,
269
+ on_closed=self._closed)
270
+
271
+ def _closed(self) -> None:
272
+ self.current = None
273
+ self.served.clear()
274
+
275
+
276
+ # ---- end pipeline -------------------------------------------------------------------
277
+
278
+ def _state_word(state: str | None) -> str:
279
+ state = state or "not_started"
280
+ return f"{levels.GLYPH[state]} {levels.LABEL[state]}"
281
+
282
+
283
+ def _minutes(started: datetime, ended: datetime) -> int:
284
+ return max(0, round((ended - started).total_seconds() / 60))
285
+
286
+
287
+ def _session_md(sid, mode, started, ended, counts, rows, unchecked, summary,
288
+ changes=(), left_out: int = 0) -> str:
289
+ """`left_out`: how many private or hidden topics `_end` kept off the page."""
290
+ mins = _minutes(started, ended)
291
+ lines = [f"# Session {sid}", "",
292
+ f"- Mode: {mode}",
293
+ f"- Started: {started.astimezone():%Y-%m-%d %H:%M}",
294
+ f"- Duration: {mins} min",
295
+ "- Counts: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in COUNT_KINDS),
296
+ "", "## Concepts"]
297
+ lines += [f"- {render.esc(r['title'])} ({r['id']}): {_state_word(r['before'])} → "
298
+ f"{_state_word(r['after'])}" for r in rows] or ([] if left_out else ["- none"])
299
+ if left_out:
300
+ lines.append(f"- {left_out} private topic{'s' if left_out > 1 else ''} not listed.")
301
+ lines += ["", "## Taught, not yet checked"]
302
+ lines += [f"- {render.esc(u['title'])} ({u['id']})" for u in unchecked] or ["- none"]
303
+ if changes:
304
+ lines += ["", "## Changed", *render.changed_lines(changes)]
305
+ lines += ["", "## Summary", render.esc(summary, SUMMARY_MAX) if summary else "(none)", ""]
306
+ return "\n".join(lines)
307
+
308
+
309
+ def git_choice(config: dict | None = None) -> tuple[bool, bool]:
310
+ """`git:` in ~/.keepfold/config.yaml as (enabled, private_browsing). enabled (default true):
311
+ Keepfold keeps the vault's history in git. private_browsing (default false): browse/private/
312
+ is committed too, and only counts while enabled. Anything but a real true/false is its
313
+ default."""
314
+ from keepfold import taint
315
+ g = (taint.config() if config is None else config).get("git")
316
+ g = g if isinstance(g, dict) else {}
317
+ on = g.get("enabled") is not False
318
+ return on, on and g.get("private_browsing") is True
319
+
320
+
321
+ GIT_TIMEOUT_S = 60 # a hung git (pinentry, a hook, antivirus) must not hold the vault lock
322
+
323
+
324
+ def _registry_path() -> str:
325
+ """PATH as the registry holds it now (user, then machine): an install after this process
326
+ started (winget's Git) is on it, though not on os.environ's copy. Empty off Windows."""
327
+ if sys.platform != "win32":
328
+ return ""
329
+ import winreg
330
+ out = []
331
+ for hive, key in ((winreg.HKEY_CURRENT_USER, "Environment"),
332
+ (winreg.HKEY_LOCAL_MACHINE,
333
+ r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")):
334
+ try:
335
+ with winreg.OpenKey(hive, key) as k:
336
+ out.append(os.path.expandvars(str(winreg.QueryValueEx(k, "Path")[0])))
337
+ except OSError:
338
+ continue
339
+ return os.pathsep.join(out)
340
+
341
+
342
+ def git_exe() -> str | None:
343
+ """git on PATH, else where Git for Windows installs it (machine or user scope), else on
344
+ PATH as the registry has it now: a git installed while Keepfold runs is found at once."""
345
+ if found := shutil.which("git"):
346
+ return found
347
+ if sys.platform != "win32":
348
+ return None
349
+ dirs = [str(Path(base, *sub, "Git", "cmd")) for base, sub in (
350
+ (os.environ.get("ProgramFiles"), ()), (os.environ.get("LOCALAPPDATA"), ("Programs",)))
351
+ if base]
352
+ dirs += _registry_path().split(os.pathsep)
353
+ return shutil.which("git", path=os.pathsep.join(d for d in dirs if d.strip()))
354
+
355
+
356
+ def _run_git(cmd: list[str], input: str | None = None) -> subprocess.CompletedProcess:
357
+ """git with UTF-8 I/O; a timeout comes back as a failed run (returncode 1), with a warning.
358
+ `cmd[0]` "git" becomes the git `git_exe` finds."""
359
+ cmd = [git_exe() or cmd[0], *cmd[1:]]
360
+ try:
361
+ return subprocess.run(cmd, input=input, capture_output=True, encoding="utf-8",
362
+ timeout=GIT_TIMEOUT_S, creationflags=NO_WINDOW)
363
+ except subprocess.TimeoutExpired:
364
+ log.warning("vault git timed out after %d s: %s", GIT_TIMEOUT_S, " ".join(cmd[1:]))
365
+ return subprocess.CompletedProcess(cmd, 1, "", f"git timed out after {GIT_TIMEOUT_S} s")
366
+
367
+
368
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess:
369
+ return _run_git(["git", "-C", str(root), *args])
370
+
371
+
372
+ def git_busy(root: Path) -> str | None:
373
+ """Why the vault repo must not take a commit now (an unfinished revert/merge/cherry-pick
374
+ or unmerged files), else None."""
375
+ heads = ("REVERT_HEAD", "MERGE_HEAD", "CHERRY_PICK_HEAD")
376
+ paths = _git(root, "rev-parse", *(a for h in heads for a in ("--git-path", h))).stdout
377
+ for head, p in zip(heads, paths.splitlines(), strict=False):
378
+ if (root / p).exists():
379
+ return f"{head} exists"
380
+ unmerged = unmerged_paths(root)
381
+ return f"unmerged files: {', '.join(unmerged)}" if unmerged else None
382
+
383
+
384
+ def unmerged_paths(root: Path) -> list[str]:
385
+ out = _git(root, "diff", "--name-only", "-z", "--diff-filter=U").stdout
386
+ return sorted(set(filter(None, out.split("\0"))))
387
+
388
+
389
+ def _gitz(root, *args: str, input: str | None = None) -> subprocess.CompletedProcess:
390
+ """git with UTF-8 I/O and literal pathspecs: file names are data, never globs."""
391
+ return _run_git(["git", "--literal-pathspecs", "-C", str(root), *args], input=input)
392
+
393
+
394
+ def _status_paths(out: str) -> list[str]:
395
+ """Repo-relative paths in `git status --porcelain -z` output, both sides of a rename."""
396
+ parts, paths, i = out.split("\0"), [], 0
397
+ while i < len(parts):
398
+ entry, i = parts[i], i + 1
399
+ if len(entry) < 4:
400
+ continue
401
+ paths.append(entry[3:])
402
+ if ("R" in entry[:2] or "C" in entry[:2]) and i < len(parts):
403
+ paths.append(parts[i]) # the rename's source
404
+ i += 1
405
+ return paths
406
+
407
+
408
+ def _rel(vault: Vault, paths) -> set[str]:
409
+ return {Path(p).relative_to(vault.root).as_posix() for p in paths
410
+ if Path(p).is_relative_to(vault.root)}
411
+
412
+
413
+ def _commit_paths(top: str, paths: list[str], message: str) -> bool:
414
+ """Stage and commit exactly `paths` (a pathspec commit leaves anything else in the index)."""
415
+ if gone := [p for p in paths if not (Path(top) / p).exists()]:
416
+ # a new file deleted since the snapshot (B12: we run outside the lock) matches no
417
+ # pathspec and would fail the whole add; a tracked one's deletion is committed
418
+ tracked = set(_gitz(top, "ls-files", "-z").stdout.split("\0"))
419
+ paths = [p for p in paths if p not in gone or p in tracked]
420
+ if not paths:
421
+ return False
422
+ spec = "\0".join(paths)
423
+ for args in (("add", "-A"), ("commit", "-q", "-m", message)):
424
+ r = _gitz(top, *args, "--pathspec-from-file=-", "--pathspec-file-nul", input=spec)
425
+ if r.returncode:
426
+ log.warning("vault git %s failed: %s", args[0], r.stderr.strip())
427
+ return False
428
+ return True
429
+
430
+
431
+ def _stat(top: str, rel: str) -> tuple[int, int, int] | None:
432
+ """(size, mtime_ns, file id) of a repo-relative path, None if missing. The file id catches
433
+ an atomic replace (vault writes) even within one mtime tick; an in-place rewrite of the same
434
+ size within one tick is not caught (accepted: hand editors replace or change the size)."""
435
+ try:
436
+ st = os.stat(Path(top) / rel)
437
+ except OSError:
438
+ return None
439
+ return st.st_size, st.st_mtime_ns, st.st_ino
440
+
441
+
442
+ def _unchanged(top: str, paths: list[str], stats: dict[str, tuple | None]) -> list[str]:
443
+ """`paths` whose stat still matches the locked snapshot; a file another writer changed
444
+ since is left uncommitted for the commit of whoever owns it next."""
445
+ keep = []
446
+ for rel in paths:
447
+ if _stat(top, rel) == stats[rel]:
448
+ keep.append(rel)
449
+ else:
450
+ log.debug("vault commit left %s for a later commit: it changed after the snapshot",
451
+ rel)
452
+ return keep
453
+
454
+
455
+ SCAN_MAX_BYTES = 1 << 20 # r1-trust T7: larger files (exports, media) are not scanned
456
+
457
+
458
+ def _withhold_secrets(top: str, paths: list[str], withheld: list[str]) -> list[str]:
459
+ """v6 T7: drop from `paths` (repo-relative) each file that looks like it holds a key, so it
460
+ stays uncommitted; only the files about to be committed are read, never the whole vault.
461
+ Each drop is logged and added to `withheld` as "<path>: <pattern>", never the secret."""
462
+ keep = []
463
+ for rel in paths:
464
+ p = Path(top) / rel
465
+ try:
466
+ hit = p.is_file() and p.stat().st_size <= SCAN_MAX_BYTES and secret_pattern(
467
+ p.read_bytes().decode("utf-8", errors="ignore"))
468
+ except OSError:
469
+ hit = None
470
+ if hit:
471
+ withheld.append(f"{rel}: {hit}")
472
+ log.warning("vault commit left %s uncommitted: it matches secret pattern %s; "
473
+ "remove the key and close again", rel, hit)
474
+ else:
475
+ keep.append(rel)
476
+ return keep
477
+
478
+
479
+ def _commit(vault: Vault, message: str, mine=None, *, before: str | None = None,
480
+ exclude=(), withheld: list[str] | None = None) -> str | None:
481
+ """Commit in the vault repo. With `mine` (vault file paths), only those of them that
482
+ changed go in, and every other change, less `exclude`, first gets its own commit `before`
483
+ (with no `before` it stays uncommitted); with no `mine`, every change goes in. A changed
484
+ file that matches a secret pattern stays uncommitted and is named in `withheld`. Returns
485
+ the `message` commit, or None if git is off in settings, not a repo, none of ours changed,
486
+ a revert/merge is in progress, or git failed."""
487
+ withheld = [] if withheld is None else withheld
488
+ enabled, keep_private = git_choice()
489
+ if not enabled: # the owner's choice: no history; an existing .git is left as it is
490
+ return None
491
+ with vault.lock():
492
+ top = _gitz(vault.root, "rev-parse", "--show-toplevel")
493
+ if top.returncode:
494
+ return None
495
+ top = top.stdout.strip()
496
+ from keepfold.browse.forget import PRIVATE_IGNORE
497
+
498
+ status = _gitz(top, "status", "--porcelain", "-z", "--untracked-files=all")
499
+ pre = _gitz(vault.root, "rev-parse", "--show-prefix").stdout.strip()
500
+ # C3: a private browse page still in the index (staged, or tracked before the ignore
501
+ # line) is never committed; `untrack_private` takes it out of the index. With
502
+ # `git.private_browsing` on, the owner chose to commit it like any other page.
503
+ # C5: nor is a page in the chat archive, even with its .gitignore line missing
504
+ changed = [c for c in _status_paths(status.stdout)
505
+ if (keep_private or not c.startswith(pre + PRIVATE_IGNORE))
506
+ and not c.startswith(pre + CHAT_ARCHIVE + "/")]
507
+ if status.returncode or not changed:
508
+ return None
509
+ if busy := git_busy(vault.root):
510
+ log.warning("vault commit skipped (%s); finish or abort it in git first", busy)
511
+ return None
512
+ ours, other = changed, []
513
+ if mine is not None:
514
+ keys = {pre + r for r in _rel(vault, mine)}
515
+ skip = {pre + r for r in _rel(vault, exclude)}
516
+ ours = [c for c in changed if c in keys]
517
+ other = [c for c in changed if c not in keys and c not in skip] if before else []
518
+ stats = {c: _stat(top, c) for c in ours + other}
519
+ # B12: the lock covered only the snapshot and the path lists; the scan, add and commit run
520
+ # on those exact paths outside it, so other writers never wait on git. A file another
521
+ # writer changed meanwhile (its stat differs from the snapshot's) is dropped right before
522
+ # the add and stays modified for its owner's next commit, so this commit never holds
523
+ # another session's text and `undo` stays per session. The window left is the few ms
524
+ # between that re-stat and git reading the file. A revert or merge begun meanwhile makes
525
+ # git refuse the pathspec commit, and a second commit's index.lock fails the add or
526
+ # commit: either way a logged warning and None.
527
+ ours = _withhold_secrets(top, ours, withheld)
528
+ other = _withhold_secrets(top, other, withheld)
529
+ if other := _unchanged(top, other, stats):
530
+ if not _commit_paths(top, other, before):
531
+ return None
532
+ ours = _unchanged(top, ours, stats)
533
+ if not ours or not _commit_paths(top, ours, message):
534
+ return None
535
+ # HEAD may already be another process's later commit: the newest with our message
536
+ shas = _gitz(top, "log", "-z", "-n", "20", "--format=%H %B").stdout.split("\0")
537
+ return next((h for h, _, b in (s.partition(" ") for s in shas) if b.strip() == message),
538
+ None)
539
+
540
+
541
+ _DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
542
+
543
+
544
+ def _owned(vault: Vault, events) -> dict[str, set[Path]]:
545
+ """Files each session's events show it wrote: its event files and the notes its `change`
546
+ records name (what a sweep can know of a session another process ran)."""
547
+ out: dict[str, set[Path]] = {}
548
+ for e in events:
549
+ sid, day = e.get("session"), e.get("day")
550
+ if not (isinstance(sid, str) and sid.startswith("s_") and SESSION_RE.fullmatch(sid)
551
+ and isinstance(day, str) and _DAY_RE.fullmatch(day)):
552
+ continue
553
+ paths = out.setdefault(sid, set())
554
+ paths.add(vault.root / "events" / day[:4] / day[5:7] / f"{sid}.jsonl")
555
+ p = e.get("payload") if e.get("kind") == "change" else None
556
+ ch = p.get("change") if isinstance(p, dict) else None
557
+ if isinstance(ch, dict):
558
+ try:
559
+ paths.add(vault.path_for(ch.get("kind"), ch.get("id")))
560
+ except (VaultError, TypeError):
561
+ pass
562
+ return out
563
+
564
+
565
+ def exposed_pages(events) -> set[str]:
566
+ """v6 T3: ids of pages whose latest `change` event was written in an exposed session.
567
+ Events only, never file mtime: `_end` writes `keepfold_status` on concept pages and logs no
568
+ change, so an mtime rule would clear every touched concept on close. `events` sorted."""
569
+ latest: dict[str, bool] = {}
570
+ for e in events:
571
+ p = e.get("payload") if e.get("kind") == "change" else None
572
+ ch = p.get("change") if isinstance(p, dict) else None
573
+ if isinstance(ch, dict) and isinstance(ch.get("id"), str):
574
+ latest[ch["id"]] = p.get("exposed") is True
575
+ return {i for i, exposed in latest.items() if exposed}
576
+
577
+
578
+ def _commit_session(vault: Vault, evlog: EventLog, sid: str, mode: str, mark: int,
579
+ withheld: list[str] | None = None) -> str | None:
580
+ """Commit what this session wrote: the files this process wrote since `mark` plus what its
581
+ events show. Other changes (hand edits, CLI writes, other processes) go in a commit of
582
+ their own first, so `keepfold undo <sid>` never touches them; files other still-open
583
+ sessions own are left for those sessions' own commits."""
584
+ events = list(evlog.iter_events())
585
+ owned = _owned(vault, events)
586
+ closed = {e.get("session") for e in events if e.get("kind") == "close"}
587
+ others = set().union(*(ps for s, ps in owned.items() if s != sid and s not in closed))
588
+ return _commit(vault, f"keepfold: session {sid} {mode}",
589
+ owned.get(sid, set()) | vault.wrote_since(mark),
590
+ before=f"keepfold: other changes before session {sid}", exclude=others,
591
+ withheld=withheld)
592
+
593
+
594
+ def _end(vault: Vault, evlog: EventLog, *, sid: str, mode: str, started: datetime,
595
+ ended: datetime, counts: dict, touched: set[str], before: dict, summary: str,
596
+ changes=(), on_closed=None, mark: int = 0, ledger: int = 0,
597
+ now: datetime | None = None) -> dict:
598
+ """`mark`: vault.writes when the session started in this process; files written since
599
+ then belong to it. `ledger`: how many of counts["logged"] were LEDGER_LOG_KINDS; a session
600
+ with nothing else is quiet. `ended` dates the close event, duration and journal line;
601
+ `now` (default `ended`) the states, tool props and Today.md written at the close (B15)."""
602
+ now = now or ended
603
+ fields = {"summary": summary[:SUMMARY_MAX]} if summary else {}
604
+ with vault.lock(): # SEC-6: a sweep in another process may have closed it meanwhile
605
+ if any(e.get("kind") == "close" for e in evlog.iter_events(session=sid)):
606
+ if on_closed:
607
+ on_closed()
608
+ return {"session": sid, "mode": mode, "counts": dict(counts), "moved": [],
609
+ "unchecked": [], "today": [], "minutes": _minutes(started, ended),
610
+ "changes": list(changes), "commit": None, "already_closed": True}
611
+ evlog.append(session=sid, kind="close", source="tutor", mode=mode, fields=fields,
612
+ now=ended)
613
+ if on_closed:
614
+ on_closed() # the session is closed from here on, whatever fails below
615
+ catalog = Catalog.load(vault)
616
+ after, _ = planner.current_states(vault, local_day(now), catalog)
617
+
618
+ def title(c):
619
+ e = catalog.entries.get(c)
620
+ return e.title if e else c
621
+
622
+ rows = []
623
+ unchecked = [{"id": c, "title": title(c)} for c in planner.fresh_unchecked(
624
+ {c: after[c] for c in touched if c in after}, local_day(now))]
625
+ for c in sorted(touched):
626
+ b, a = before.get(c), after.get(c)
627
+ rows.append({"id": c, "title": title(c), "before": b.state if b else "not_started",
628
+ "after": a.state if a else "not_started"})
629
+ try:
630
+ vault.set_tool_props("concept", c, a.state if a else "not_started",
631
+ a.next_due if a else None)
632
+ except VaultError as e:
633
+ if e.code not in ("unknown_id", "invalid_id"):
634
+ raise
635
+ today = planner.today(vault, catalog, after, now=now)
636
+ quiet = not changes and counts.get("logged", 0) == ledger and not any(
637
+ counts.get(k) for k in COUNT_KINDS if k != "logged")
638
+ # the page, Today/home and the end card never name a private or hidden topic (E1 privacy
639
+ # gate); events, levels and tool props above still cover every touched concept
640
+ hide = _private_ids(vault, catalog, changes)
641
+ left = {r["id"] for r in rows if r["id"] in hide} | {
642
+ c["id"] for c in changes if c.get("id") in hide}
643
+ rows = [r for r in rows if r["id"] not in hide]
644
+ unchecked = [u for u in unchecked if u["id"] not in hide]
645
+ changes = [c for c in changes if c.get("id") not in hide]
646
+ moved = [r for r in rows if r["before"] != r["after"]]
647
+ if not quiet:
648
+ _record(vault, sid=sid, mode=mode, started=started, ended=ended, counts=counts,
649
+ rows=rows, unchecked=unchecked, summary=summary, changes=changes, today=today,
650
+ as_of=local_day(now), left_out=len(left))
651
+ withheld: list[str] = []
652
+ commit = _commit_session(vault, evlog, sid, mode, mark, withheld)
653
+ return {"session": sid, "mode": mode, "counts": dict(counts), "moved": moved,
654
+ "unchecked": unchecked, "today": today, "minutes": _minutes(started, ended),
655
+ "changes": list(changes), "commit": commit, "not_committed": withheld}
656
+
657
+ # The journal line a session close writes. AUTO_JOURNAL matches it so the portrait gate
658
+ # (reflect.portrait) can tell Keepfold's own lines from the learner's; keep the two in sync.
659
+ SESSION_LINE = "session {mode}: {changes} changes, {graded} graded"
660
+ AUTO_JOURNAL = re.compile(r"session \w+: \d+ changes, \d+ graded")
661
+
662
+
663
+ def _private_ids(vault: Vault, catalog: Catalog, changes) -> set[str]:
664
+ """The ids a session page may not name: planner.hidden (private subjects, what sits under
665
+ them, their mistakes) and the changed pages that are private themselves. People pages are
666
+ left to render._change, which never names one."""
667
+ hide = planner.hidden(vault, catalog)
668
+ for c in changes:
669
+ kind, id = c.get("kind"), c.get("id")
670
+ if kind in Vault.KIND_DIRS and kind != "person" and isinstance(id, str) \
671
+ and id not in hide:
672
+ try:
673
+ if is_private(vault.read(kind, id)):
674
+ hide.add(id)
675
+ except VaultError: # gone or unreadable: nothing to hide
676
+ pass
677
+ return hide
678
+
679
+
680
+ def _record(vault: Vault, *, sid, mode, started, ended, counts, rows, unchecked, summary,
681
+ changes, today, as_of, left_out: int = 0) -> None:
682
+ """What a non-quiet close writes besides its event and commit: journal line, session
683
+ note, Today.md (one planner pass, ~10 ms at 5k pages) and the log.md line."""
684
+ try:
685
+ vault.append_journal(local_day(ended), f"{ended.astimezone():%H:%M}",
686
+ SESSION_LINE.format(mode=mode, changes=len(changes),
687
+ graded=counts.get("graded", 0)))
688
+ except Exception: # the journal is a view of the day; it must never break close
689
+ log.exception("journal line failed")
690
+ name = f"{local_day(started)}-{mode}-{sid[-8:].lower()}"
691
+ text = _session_md(sid, mode, started, ended, counts, rows, unchecked, summary, changes,
692
+ left_out)
693
+ day = next((d for d in (local_day(started), local_day(ended))
694
+ if vault.path_for("journal", d).is_file()), None)
695
+ vault.write_text(vault.path_for("session", name),
696
+ relink.with_up(text, day) if day else text) # Obsidian: session -> day
697
+ vault.write_text(vault.root / "Today.md", render.today_md(
698
+ today=today, assessments=planner.assessments(vault), as_of=as_of,
699
+ cues=planner.last_questions(vault), deadlines=planner.deadlines(vault, as_of)))
700
+ try: # log.md is a view too; it must never break close
701
+ vault.append_log(local_day(ended), "session", f"{mode}, {len(changes)} changes")
702
+ except Exception:
703
+ log.exception("log.md line failed")
704
+
705
+
706
+ def sweep(vault: Vault, clock=datetime.now, *, force: bool = False) -> list[str]:
707
+ """Close orphan sessions (events but no `close`) idle > 2 h or whose server process has
708
+ exited (the pid in its `open` event), or all of them with `force`. A session whose server
709
+ is still alive is left open until it idles out."""
710
+ evlog = EventLog(vault)
711
+ events = list(evlog.iter_events())
712
+ by_session: dict[str, list[dict]] = {}
713
+ for ev in events:
714
+ sid = ev.get("session")
715
+ if isinstance(sid, str) and sid.startswith("s_") and SESSION_RE.fullmatch(sid):
716
+ by_session.setdefault(sid, []).append(ev)
717
+ now = _utc(clock())
718
+ closed = []
719
+ for sid, evs in by_session.items():
720
+ if any(e.get("kind") == "close" for e in evs):
721
+ continue
722
+ pid = next((e["payload"].get("pid") for e in evs if e.get("kind") == "open"
723
+ and isinstance(e.get("payload"), dict)), None)
724
+ alive = type(pid) is int and _pid_alive(pid)
725
+ gone = type(pid) is int and not alive
726
+ last = parse_ts(evs[-1]["ts"])
727
+ # B2: a live server's session may be reading for hours without an event; it closes
728
+ # itself when idle, so a sweep waits a day for it (pid reuse aside)
729
+ if not force and not gone and now - last <= (LIVE_CLOSE if alive else IDLE_CLOSE):
730
+ continue
731
+ kinds = [e.get("kind") for e in evs]
732
+ counts = dict.fromkeys(COUNT_KINDS, 0)
733
+ counts.update(asked=kinds.count("ask"), graded=kinds.count("grade"),
734
+ logged=kinds.count("log") + kinds.count("taught"))
735
+ ledger = sum(e.get("kind") == "log" and isinstance(e.get("payload"), dict)
736
+ and e["payload"].get("kind") in LEDGER_LOG_KINDS for e in evs)
737
+ touched = {o.split(":", 1)[1] for e in evs
738
+ for o in [e.get("object"), *(e.get("also") or [])]
739
+ if isinstance(o, str) and o.startswith("concept:")}
740
+ changes = []
741
+ for e in evs: # what SessionManager.note recorded, as the in-memory close sees it
742
+ p = e.get("payload") if e.get("kind") == "change" else None
743
+ if not isinstance(p, dict):
744
+ continue
745
+ if p.get("note") in ("patched", "added"):
746
+ counts[p["note"]] += 1
747
+ if isinstance(p.get("concept"), str):
748
+ touched.add(p["concept"])
749
+ if isinstance(p.get("change"), dict):
750
+ changes.append(p["change"])
751
+ mode = next((e["mode"] for e in evs if e.get("mode") in MODES), "learn")
752
+ before, _ = planner.current_states(
753
+ vault, local_day(now), events=[e for e in events if e.get("session") != sid])
754
+ if any(e.get("kind") == "close" for e in evlog.iter_events(session=sid)):
755
+ continue # another process closed it since the scan; _end re-checks under the lock
756
+ # B15: an idle or orphaned session ended at its last event (+1 s, so the close sorts
757
+ # after it); `force` closes it now
758
+ res = _end(vault, evlog, sid=sid, mode=mode, started=parse_ts(evs[0]["ts"]),
759
+ ended=now if force else min(now, last + timedelta(seconds=1)), now=now,
760
+ counts=counts, touched=touched, before=before, summary="auto-closed",
761
+ changes=changes, mark=vault.writes, ledger=ledger) # another process ran it
762
+ if not res.get("already_closed"):
763
+ closed.append(sid)
764
+ return closed