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/vault.py ADDED
@@ -0,0 +1,942 @@
1
+ """Vault parsing and safe writes: lock, atomic replace, ID and path checks, secret scan.
2
+
3
+ This is the only module that touches vault files (SPEC §4, CLAUDE.md).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import functools
10
+ import io
11
+ import itertools
12
+ import json
13
+ import logging
14
+ import os
15
+ import re
16
+ import socket
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import threading
21
+ import time
22
+ from collections.abc import Callable, Iterator
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+ from datetime import date
26
+ from pathlib import Path, PurePath
27
+
28
+ from ruamel.yaml import YAML
29
+ from ruamel.yaml.comments import CommentedMap, CommentedSeq
30
+ from ruamel.yaml.scalarstring import DoubleQuotedScalarString
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ ID_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{0,80}$")
35
+ # The private browse folder, vault-relative: kept from Claude, git and the index.
36
+ PRIVATE_BROWSE_DIR = "browse/private"
37
+ # C5: imported AI chat pages (resources), vault-relative; git-ignored, read like resources/
38
+ CHAT_ARCHIVE = "archive/chats"
39
+
40
+ # SPEC §15a.2: fields marked * per kind. TOOL_PROPS are written only by set_tool_props.
41
+ SET_FIELD_WHITELIST = {
42
+ "problem": {"status", "solved_on"},
43
+ "assessment": {"date", "outcome", "score", "summary"},
44
+ "application": {"status"},
45
+ "track": {"current_day"},
46
+ "resource": {"status", "summary", "url"},
47
+ "note": {"summary"},
48
+ "project": {"status", "summary"},
49
+ "decision": {"status", "summary", "review_on"},
50
+ "loop": {"status", "due", "summary"},
51
+ }
52
+ TOOL_PROPS = {"keepfold_status", "keepfold_next"}
53
+ ENUMS = {
54
+ ("problem", "status"): {"todo", "attempted", "solved"},
55
+ # taken: the test is done and the result is not out yet; only pending counts as coming up
56
+ ("assessment", "outcome"): {"pending", "taken", "pass", "fail", "unknown"},
57
+ ("application", "status"): {"applied", "oa", "interview", "offer", "rejected", "withdrawn"},
58
+ # phase4-wiki.md §2, §2a
59
+ ("resource", "resource_type"): {"book", "paper", "course", "video", "repo", "article", "other"},
60
+ ("resource", "status"): {"queued", "reading", "done", "reference"},
61
+ ("note", "note_type"): {"fleeting", "literature", "permanent", "structure"},
62
+ ("project", "status"): {"idea", "active", "paused", "shipped", "archived"},
63
+ ("decision", "status"): {"proposed", "accepted", "superseded", "retired"},
64
+ ("loop", "status"): {"open", "done", "dropped"},
65
+ ("loop", "loop_type"): {"commitment", "question", "idea"},
66
+ }
67
+
68
+ SECRET_RES = [
69
+ re.compile(r"\bsk-[A-Za-z0-9_-]{20,}"),
70
+ re.compile(r"\bghp_[A-Za-z0-9]{20,}"),
71
+ re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"),
72
+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
73
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
74
+ re.compile(r"api[_-]?key\s*[:=]\s*\S{12,}", re.IGNORECASE),
75
+ re.compile(r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}"), # Stripe
76
+ re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"), # Slack
77
+ re.compile(r"\bAIza[0-9A-Za-z_-]{35}"), # Google API key
78
+ re.compile(r"\bglpat-[A-Za-z0-9_-]{20,}"), # GitLab
79
+ re.compile(r"\bhf_[A-Za-z]{30,}"), # Hugging Face
80
+ re.compile(r"\bnpm_[A-Za-z0-9]{36}"),
81
+ re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), # JWT
82
+ re.compile(r"\b[a-z][a-z0-9+.-]*://[^\s/:@]+:[^\s/@]+@"), # credentials in a URL
83
+ re.compile(r"\bpassword\s*[:=]\s*\S{6,}", re.IGNORECASE),
84
+ # a 64-hex value soon after a private-key word (pasted wallet keys); bare tx hashes pass
85
+ re.compile(r"priv(?:ate)?[_ -]?key[^\n]{0,40}?(?<![0-9a-f])(?:0x)?[0-9a-f]{64}(?![0-9a-f])",
86
+ re.IGNORECASE),
87
+ ]
88
+
89
+ # path -> ((ino, mtime_ns, size), fields, body): in-process only, so re-reads skip the YAML parse.
90
+ # shortcut: a same-size in-place rewrite within one mtime tick is missed (FAT: 2 s ticks).
91
+ _PARSED: dict[Path, tuple[tuple[int, ...], CommentedMap, str]] = {}
92
+
93
+ HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.*?)[ \t]*$")
94
+ UNCHECKED_RE = re.compile(r"^\s*[-*] \[ \] ")
95
+ CHECKED_RE = re.compile(r"^\s*[-*] \[[xX]\] ")
96
+
97
+ LOCK_STALE_S = 120
98
+ REPLACE_TRIES = 8
99
+ # lock tokens this process holds now: a lock file with this pid and another token is one it
100
+ # failed to delete (Windows refuses while another process reads it), so never a live holder
101
+ _HELD: set[str] = set()
102
+ _SEQ = itertools.count()
103
+ # a token's "born" and the holder's start time read later may differ by this much: born is
104
+ # written to the second, and ps's etime (macOS) counts whole seconds
105
+ _BORN_TOL_S = 3
106
+ # Windows creation times never move; /proc's and ps's are now-relative and shift with a clock step
107
+ _FIXED_START = os.name == "nt"
108
+
109
+
110
+ def in_temp_folder(p: Path | str) -> bool:
111
+ """Whether `p` lies inside the system temp folder (path parts, not a string prefix;
112
+ case-insensitive on Windows). Windows can empty that folder at any time."""
113
+ try:
114
+ t, q = Path(tempfile.gettempdir()).resolve().parts, Path(p).resolve().parts
115
+ except OSError:
116
+ return False
117
+ if os.name == "nt":
118
+ t, q = tuple(x.casefold() for x in t), tuple(x.casefold() for x in q)
119
+ return q[:len(t)] == t
120
+
121
+
122
+ def sqlite_ro_uri(p: PurePath) -> str:
123
+ """A read-only SQLite URI for `p`. SQLite rejects a URI authority, so a UNC path (a share,
124
+ or a mapped drive after resolve()) keeps an empty one: file:////server/share/..."""
125
+ u = p.as_uri()
126
+ return ("file:////" + u[len("file://"):] if not u.startswith("file:///") else u) + "?mode=ro"
127
+
128
+
129
+ class VaultError(Exception):
130
+ """A vault failure with a tool error code from docs/tools.md."""
131
+
132
+ def __init__(self, code: str, message: str, did_you_mean: list[str] | None = None):
133
+ super().__init__(message)
134
+ self.code = code
135
+ self.did_you_mean = did_you_mean
136
+
137
+
138
+ def invalid(msg: str) -> VaultError:
139
+ return VaultError("invalid_argument", msg)
140
+
141
+
142
+ def check_day(name: str, value) -> None:
143
+ """B10: YYYY-MM-DD and a real day, or the exam clock silently skips the note."""
144
+ try:
145
+ ok = bool(isinstance(value, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", value)
146
+ and date.fromisoformat(value))
147
+ except ValueError:
148
+ ok = False
149
+ if not ok:
150
+ raise invalid(f"{name} must be a date like 2026-11-30.")
151
+
152
+
153
+ @dataclass
154
+ class Note:
155
+ path: Path
156
+ kind: str
157
+ id: str
158
+ fields: CommentedMap
159
+ body: str
160
+
161
+
162
+ TRUTHY = {"true", "yes", "y", "on", "1"}
163
+
164
+
165
+ def truthy(v) -> bool:
166
+ """A frontmatter flag set in any truthy form a person might type: true, yes, y, on, 1
167
+ (any case, quoted or not)."""
168
+ return v is True or str(v).strip().casefold() in TRUTHY
169
+
170
+
171
+ def is_private(note: Note) -> bool:
172
+ # v5 PHASE4 V4: people pages are private unless their frontmatter says `private: false`
173
+ p = note.fields.get("private")
174
+ return truthy(p) or (note.kind == "person" and p is not False)
175
+
176
+
177
+ def secret_pattern(text: str) -> str | None:
178
+ """The first SECRET_RES pattern `text` matches (the regex, never the match), or None."""
179
+ return next((rx.pattern for rx in SECRET_RES if rx.search(text)), None)
180
+
181
+
182
+ def scan_secrets(text: str) -> None:
183
+ if secret_pattern(text):
184
+ raise VaultError("secret_detected", "The text looks like it holds a key or token; "
185
+ "remove it and try again.")
186
+
187
+
188
+ def _yaml() -> YAML:
189
+ y = YAML(typ="rt")
190
+ y.preserve_quotes = True
191
+ y.width = 1_000_000 # never wrap
192
+ return y
193
+
194
+
195
+ def _split(text: str) -> tuple[str, str, str, str] | None:
196
+ """Split into (open fence, frontmatter, close fence, body), or None without frontmatter."""
197
+ m = re.match(r"\ufeff?---[ \t]*(\r?\n)", text) # an optional BOM stays in the open fence
198
+ if not m:
199
+ return None
200
+ close = re.compile(r"^---[ \t]*(\r?\n|\Z)", re.M).search(text, m.end())
201
+ if not close:
202
+ raise ValueError("frontmatter fence is not closed")
203
+ return text[: m.end()], text[m.end() : close.start()], close.group(0), text[close.end() :]
204
+
205
+
206
+ def _newline(text: str) -> str:
207
+ return "\r\n" if text.split("\n", 1)[0].endswith("\r") else "\n"
208
+
209
+
210
+ _FLAT = re.compile(r'([A-Za-z_][\w-]*): ("(?:[^"\\]|\\.)*"|-?(?:0|[1-9][0-9]*)|true|false)')
211
+
212
+
213
+ def _flat_fm(fm: str) -> CommentedMap | None:
214
+ """Flat `key: "json string" | int | true | false` lines (generated pages, sites._fm) read
215
+ without ruamel, which took ~5 ms a page (R2-10: minutes for 20k site pages), to the values
216
+ and types ruamel gives them; None for anything else."""
217
+ out = CommentedMap()
218
+ for line in fm.splitlines():
219
+ m = _FLAT.fullmatch(line)
220
+ if not m or m[1] in out:
221
+ return None
222
+ v = m[2]
223
+ if v[0] == '"':
224
+ try:
225
+ out[m[1]] = DoubleQuotedScalarString(json.loads(v))
226
+ except ValueError: # an escape JSON lacks, such as \x41: ruamel reads it
227
+ return None
228
+ else:
229
+ out[m[1]] = v == "true" if v in ("true", "false") else int(v)
230
+ return out
231
+
232
+
233
+ def _load_fm(fm: str) -> CommentedMap:
234
+ if (flat := _flat_fm(fm)) is not None:
235
+ return flat
236
+ data = _yaml().load(fm) if fm.strip() else CommentedMap()
237
+ if data is None:
238
+ return CommentedMap()
239
+ if not isinstance(data, CommentedMap):
240
+ raise ValueError("frontmatter is not a mapping")
241
+ return data
242
+
243
+
244
+ OWN_PARSE_ERRORS = ("frontmatter fence is not closed", "frontmatter is not a mapping")
245
+
246
+
247
+ def parse_error(e: BaseException, skip: int = 1) -> str:
248
+ """A parse error as its class and 1-based file line only, for logs and MCP errors: ruamel's
249
+ text quotes the offending line, which may be private. `skip`: the lines before the YAML (a
250
+ page's front matter starts after its `---` fence)."""
251
+ mark = getattr(e, "problem_mark", None) or getattr(e, "context_mark", None)
252
+ line = getattr(mark, "line", None)
253
+ if str(e) in OWN_PARSE_ERRORS: # _split/_load_fm's own words, which hold no note text
254
+ return str(e)
255
+ return type(e).__name__ + (f" at line {line + 1 + skip}" if line is not None else "")
256
+
257
+
258
+ def _dump_fm(data: CommentedMap, nl: str) -> str:
259
+ buf = io.StringIO()
260
+ _yaml().dump(data, buf)
261
+ out = buf.getvalue()
262
+ return out.replace("\n", nl) if nl != "\n" else out
263
+
264
+
265
+ def _to_yaml(value):
266
+ """Plain Python values to the vault format: quoted strings, flow-style lists and maps."""
267
+ if isinstance(value, str):
268
+ return DoubleQuotedScalarString(value)
269
+ if isinstance(value, (list, tuple)):
270
+ seq = CommentedSeq(_to_yaml(v) for v in value)
271
+ seq.fa.set_flow_style()
272
+ return seq
273
+ if isinstance(value, dict):
274
+ m = CommentedMap((_to_yaml(k), _to_yaml(v)) for k, v in value.items())
275
+ m.fa.set_flow_style()
276
+ return m
277
+ return value
278
+
279
+
280
+ def _section(lines: list[str], heading: str) -> tuple[int, int]:
281
+ """Return [start, end) line indexes of the section under `heading` (text without #s)."""
282
+ want = heading.lstrip("#").strip()
283
+ for i, line in enumerate(lines):
284
+ m = HEADING_RE.match(line.rstrip("\r\n"))
285
+ if m and m.group(2) == want:
286
+ level = len(m.group(1))
287
+ for j in range(i + 1, len(lines)):
288
+ n = HEADING_RE.match(lines[j].rstrip("\r\n"))
289
+ if n and len(n.group(1)) <= level:
290
+ return i + 1, j
291
+ return i + 1, len(lines)
292
+ raise VaultError("invalid_argument", f"Heading '{want}' is not in the note; "
293
+ "use an existing heading.")
294
+
295
+
296
+ def _touch(path: Path) -> None:
297
+ try:
298
+ path.read_bytes()
299
+ except OSError:
300
+ pass
301
+
302
+
303
+ def warm(paths: list[Path]) -> None:
304
+ """Read files once in parallel before a sequential parse: the first open of a newly
305
+ written file waits for the antivirus scan (~9 ms each here, R2-10), and scans overlap."""
306
+ from concurrent.futures import ThreadPoolExecutor
307
+
308
+ with ThreadPoolExecutor(16) as ex:
309
+ list(ex.map(_touch, paths))
310
+
311
+
312
+ def _pid_alive(pid: int) -> bool:
313
+ if pid == os.getpid():
314
+ return True
315
+ if os.name == "nt":
316
+ # os.kill(pid, 0) would terminate the process on Windows; query it instead.
317
+ import ctypes
318
+
319
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
320
+ h = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
321
+ if not h:
322
+ return ctypes.get_last_error() == 5 # access denied: it exists
323
+ code = ctypes.c_ulong()
324
+ ok = k32.GetExitCodeProcess(h, ctypes.byref(code))
325
+ k32.CloseHandle(h)
326
+ return bool(ok) and code.value == 259 # STILL_ACTIVE
327
+ try:
328
+ os.kill(pid, 0)
329
+ except ProcessLookupError:
330
+ return False
331
+ except PermissionError:
332
+ return True
333
+ return True
334
+
335
+
336
+ def _etime_s(out: str) -> int | None:
337
+ """Seconds in ps's etime output, `[[dd-]hh:]mm:ss`, or None when it is not that."""
338
+ m = re.fullmatch(r"\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*", out)
339
+ if not m:
340
+ return None
341
+ d, h, mm, ss = (int(g or 0) for g in m.groups())
342
+ return ((d * 24 + h) * 60 + mm) * 60 + ss
343
+
344
+
345
+ def _pid_started(pid: int) -> float | None:
346
+ """When process `pid` started (epoch seconds), or None when that cannot be read."""
347
+ try:
348
+ if sys.platform == "darwin": # no /proc: ps's elapsed time is locale-free
349
+ from keepfold._proc import NO_WINDOW
350
+ secs = _etime_s(subprocess.run(["ps", "-o", "etime=", "-p", str(pid)],
351
+ capture_output=True, text=True, timeout=2,
352
+ creationflags=NO_WINDOW).stdout)
353
+ return None if secs is None else time.time() - secs
354
+ if os.name == "nt":
355
+ import ctypes
356
+ from ctypes import wintypes
357
+
358
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
359
+ k32.OpenProcess.restype = wintypes.HANDLE
360
+ h = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
361
+ if not h:
362
+ return None
363
+ t = [wintypes.FILETIME() for _ in range(4)]
364
+ ok = k32.GetProcessTimes(wintypes.HANDLE(h), *map(ctypes.byref, t))
365
+ k32.CloseHandle(wintypes.HANDLE(h))
366
+ # creation time: 100 ns ticks since 1601
367
+ return ((t[0].dwHighDateTime << 32 | t[0].dwLowDateTime) / 1e7 - 11644473600
368
+ if ok else None)
369
+ # field 22 of /proc/<pid>/stat: clock ticks since boot; /proc/stat btime: the boot
370
+ ticks = int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[19])
371
+ boot = next(float(line.split()[1]) for line in
372
+ Path("/proc/stat").read_text().splitlines() if line.startswith("btime "))
373
+ return boot + ticks / os.sysconf("SC_CLK_TCK")
374
+ except (OSError, ValueError, IndexError, StopIteration, AttributeError,
375
+ subprocess.SubprocessError):
376
+ return None
377
+
378
+
379
+ @functools.cache
380
+ def _born(pid: int) -> float:
381
+ """This process's start time for its lock tokens (keyed by pid, so a fork reads its own); 0
382
+ when unknown."""
383
+ return _pid_started(pid) or 0
384
+
385
+
386
+ class Vault:
387
+ KIND_DIRS = {
388
+ "concept": "concepts", "area": "areas", "domain": "domains", "mistake": "mistakes",
389
+ "problem": "problems", "assessment": "assessments", "application": "applications",
390
+ "track": "tracks", "session": "sessions", "me": "me", "resource": "resources",
391
+ "note": "notes", "project": "projects", "decision": "decisions",
392
+ "journal": "journal", "loop": "loops", "person": "people",
393
+ "browse": "browse", # browse-brain.md §3: generated day pages; browse/private/ is not read
394
+ "rollup": "rollups", # keepfold.rollups: generated week, month and year pages
395
+ }
396
+ # more folders a kind's pages may sit in, read like its own; a new page goes to the main
397
+ # folder unless create_note names one of these (keepfold.chat_archive)
398
+ EXTRA_DIRS = {"resource": (CHAT_ARCHIVE,)}
399
+
400
+ @classmethod
401
+ def dirs(cls, kind: str) -> tuple[str, ...]:
402
+ """A kind's folders, vault-relative: its own, then EXTRA_DIRS."""
403
+ return (cls.KIND_DIRS[kind], *cls.EXTRA_DIRS.get(kind, ()))
404
+
405
+ def __init__(self, root: Path):
406
+ self.root = Path(root).resolve()
407
+ # the move from Cortex (keepfold.migrate), before anything reads or writes .keepfold/:
408
+ # a set lookup after the first Vault of this root, two stats with nothing to move
409
+ from keepfold import migrate
410
+ if why := migrate.on_open(self.root):
411
+ raise VaultError("vault_locked", why)
412
+ self._tlock = threading.RLock()
413
+ self._depth = 0
414
+ self._jobs: set[tuple[str, int]] = set() # (job lock, thread) held, see job_lock
415
+ # path -> write number of its last write or removal, so a session close or a CLI
416
+ # command commits only the files this process wrote (see wrote_since)
417
+ self.written: dict[Path, int] = {}
418
+ self.writes = 0
419
+
420
+ def _track(self, path: Path) -> None:
421
+ self.writes += 1
422
+ self.written[Path(path)] = self.writes
423
+
424
+ def wrote_since(self, mark: int) -> set[Path]:
425
+ """Files written or removed through this Vault after `self.writes` was `mark`."""
426
+ return {p for p, n in list(self.written.items()) if n > mark}
427
+
428
+ # ---- paths ------------------------------------------------------------
429
+
430
+ def path_for(self, kind: str, id: str) -> Path:
431
+ if kind not in self.KIND_DIRS:
432
+ raise VaultError("invalid_argument", f"Unknown kind '{kind}'; use one of "
433
+ f"{', '.join(self.KIND_DIRS)}.")
434
+ if not isinstance(id, str) or not ID_RE.fullmatch(id):
435
+ raise VaultError("invalid_id", "IDs must match ^[a-z0-9][a-z0-9.-]{0,80}$.")
436
+ path = self._contained(self.root / self.KIND_DIRS[kind] / f"{id}.md")
437
+ if not path.is_file(): # an extra folder's page; else the main folder's path
438
+ return next((p for d in self.EXTRA_DIRS.get(kind, ())
439
+ if (p := self._contained(self.root / d / f"{id}.md")).is_file()), path)
440
+ return path
441
+
442
+ def _contained(self, path: Path) -> Path:
443
+ p = Path(path)
444
+ p = (p if p.is_absolute() else self.root / p).resolve()
445
+ if not p.is_relative_to(self.root):
446
+ raise VaultError("invalid_id", "The path must stay inside the vault.")
447
+ return p
448
+
449
+ # ---- reading ----------------------------------------------------------
450
+
451
+ def _parse(self, path: Path, kind: str) -> Note:
452
+ st = path.stat() # before the read: a change after it misses the cache next time
453
+ key = (st.st_ino, st.st_mtime_ns, st.st_size) # an atomic replace gets a new file id
454
+ hit = _PARSED.get(path)
455
+ # key[1:]: dashboard._snapshot_parses seeds from the index snapshot, which has no inode
456
+ if hit is None or hit[0] not in (key, key[1:]):
457
+ text = path.read_bytes().decode("utf-8")
458
+ parts = _split(text)
459
+ fields = CommentedMap() if parts is None else _load_fm(parts[1])
460
+ hit = _PARSED[path] = (key, fields, text if parts is None else parts[3])
461
+ # shortcut: a shallow copy guards top-level edits only; nested lists are shared, and
462
+ # no caller mutates them. Deep-copy here if one ever must.
463
+ return Note(path, kind, path.stem, copy.copy(hit[1]), hit[2])
464
+
465
+ def read(self, kind: str, id: str) -> Note:
466
+ path = self.path_for(kind, id)
467
+ if not path.is_file():
468
+ raise VaultError("unknown_id", f"No {kind} note '{id}'; check the id with find.")
469
+ try:
470
+ return self._parse(path, kind)
471
+ except Exception as e: # YAML, fence or encoding errors
472
+ raise VaultError("invalid_argument",
473
+ f"{path.name} cannot be parsed: {parse_error(e)}") from e
474
+
475
+ def read_path(self, path: Path) -> Note:
476
+ """Read a vault file outside the kind folders, such as BRIEF.md, Today.md or inbox.md."""
477
+ p = self._contained(path)
478
+ if not p.is_file():
479
+ raise VaultError("unknown_id", f"{p.name} does not exist in the vault.")
480
+ kinds = {d: k for k, d in self.KIND_DIRS.items()}
481
+ extra = {d: k for k, ds in self.EXTRA_DIRS.items() for d in ds}
482
+ try:
483
+ return self._parse(p, "file" if p.parent == self.root else
484
+ extra.get(p.parent.relative_to(self.root).as_posix())
485
+ or kinds.get(p.parent.name, "file"))
486
+ except Exception as e:
487
+ raise VaultError("invalid_argument",
488
+ f"{p.name} cannot be parsed: {parse_error(e)}") from e
489
+
490
+ def note_paths(self, kind: str) -> list[Path]:
491
+ """The .md files of a kind folder (note_entries)."""
492
+ return [Path(e.path) for e in self.note_entries(kind)]
493
+
494
+ def note_entries(self, kind: str) -> Iterator[os.DirEntry]:
495
+ """The directory entries of a kind folder's .md files: the one folder rule of
496
+ note_paths and the index's scan. browse/ is read recursively (the site pages sit in
497
+ browse/sites/<category>/) except its private/ subfolder, which is never entered."""
498
+ deep = kind == "browse"
499
+ hidden = os.path.normcase(self.root / PRIVATE_BROWSE_DIR)
500
+ todo = [str(self.root / d) for d in reversed(
501
+ (self.KIND_DIRS[kind],) if deep else self.dirs(kind))]
502
+ while todo:
503
+ try:
504
+ with os.scandir(todo.pop()) as it:
505
+ entries = list(it)
506
+ except OSError: # no such folder (yet), or not a folder
507
+ continue
508
+ sub = []
509
+ for e in entries:
510
+ if os.path.normcase(e.name).endswith(".md"): # as glob: any case on Windows
511
+ yield e
512
+ if deep and e.is_dir(follow_symlinks=False) and os.path.normcase(
513
+ e.path) != hidden:
514
+ sub.append(e.path)
515
+ todo += reversed(sub)
516
+
517
+ def iter_notes(self, kind: str | None = None) -> Iterator[Note]:
518
+ kinds = [kind] if kind else list(self.KIND_DIRS)
519
+ sites = self.root / self.KIND_DIRS["browse"] / "sites"
520
+ for k in kinds:
521
+ if k not in self.KIND_DIRS:
522
+ raise VaultError("invalid_argument", f"Unknown kind '{k}'.")
523
+ for path in sorted(self.note_paths(k)):
524
+ # browse site pages (browse/sites/<category>/, up to tens of thousands) are
525
+ # for find and recall, which read note_paths; whole-vault walks skip them (R2-10)
526
+ if path.parent.parent == sites:
527
+ continue
528
+ if not ID_RE.fullmatch(path.stem):
529
+ log.warning("skipping %s: file name is not a valid id", path)
530
+ continue
531
+ try:
532
+ yield self._parse(path, k)
533
+ except Exception as e:
534
+ log.warning("skipping %s: %s", path, parse_error(e))
535
+
536
+ # ---- lock ---------------------------------------------------------------
537
+
538
+ @contextmanager
539
+ def lock(self, timeout: float = 5.0):
540
+ """Exclusive vault lock: .keepfold/lock (O_EXCL) holding "pid ts host". Reentrant per
541
+ Vault."""
542
+ if not self._tlock.acquire(timeout=timeout):
543
+ raise VaultError("vault_locked", "The vault is busy; try again in a moment.")
544
+ try:
545
+ if self._depth == 0:
546
+ self._acquire_file(timeout)
547
+ self._depth += 1
548
+ try:
549
+ yield
550
+ finally:
551
+ self._depth -= 1
552
+ if self._depth == 0:
553
+ self._release_file()
554
+ finally:
555
+ self._tlock.release()
556
+
557
+ @contextmanager
558
+ def job_lock(self, rel: str, timeout: float, busy: str):
559
+ """A lock file `rel` for a long job (a browse import), apart from the vault lock so
560
+ short writes go on meanwhile: the same "pid ts host" file and stale rules (a crashed
561
+ holder never leaves it stuck), reentrant per Vault and thread. VaultError("busy",
562
+ `busy`) when another holder keeps it past `timeout`."""
563
+ key = (rel, threading.get_ident())
564
+ if key in self._jobs:
565
+ yield
566
+ return
567
+ path = self.root / rel
568
+ try:
569
+ token = self._take(path, timeout)
570
+ except VaultError:
571
+ raise VaultError("busy", busy) from None
572
+ self._jobs.add(key)
573
+ try:
574
+ yield
575
+ finally:
576
+ self._jobs.discard(key)
577
+ self._drop(path, token)
578
+
579
+ @property
580
+ def _lock_path(self) -> Path:
581
+ return self.root / ".keepfold" / "lock"
582
+
583
+ def _acquire_file(self, timeout: float) -> None:
584
+ self._token = self._take(self._lock_path, timeout)
585
+
586
+ def _take(self, path: Path, timeout: float) -> str:
587
+ path.parent.mkdir(parents=True, exist_ok=True)
588
+ deadline = time.monotonic() + timeout
589
+ while True:
590
+ # 3 counter digits after the ms keep tokens unique: before Python 3.13 time.time() on
591
+ # Windows ticks every 15.6 ms, so two takes in one tick shared a token, the loser's
592
+ # discard unmarked the holder's, and its live lock looked like a leftover to steal
593
+ # the 4th field, born, is this process's start time (audit #2). An older Keepfold
594
+ # splits it into the host, sees another PC and applies the 120 s age rule: the same
595
+ # as a hostname change, accepted
596
+ token = (f"{os.getpid()} {time.time():.3f}{next(_SEQ) % 1000:03d} "
597
+ f"{socket.gethostname()} {_born(os.getpid()):.0f}")
598
+ _HELD.add(token) # before the file shows it, so no reader takes it for a leftover
599
+ try:
600
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
601
+ except (FileExistsError, PermissionError):
602
+ _HELD.discard(token)
603
+ if self._steal_if_stale(path):
604
+ continue
605
+ if time.monotonic() >= deadline:
606
+ raise VaultError("vault_locked", "Another Keepfold process holds the vault "
607
+ "lock; try again in a moment.") from None
608
+ time.sleep(0.05)
609
+ continue
610
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
611
+ f.write(token)
612
+ return token
613
+
614
+ def _steal_if_stale(self, path: Path) -> bool:
615
+ try:
616
+ content = path.read_text(encoding="utf-8", errors="replace")
617
+ age = time.time() - path.stat().st_mtime
618
+ except OSError:
619
+ return False # vanished or being written; retry the create
620
+ if content in _HELD:
621
+ return False # this process holds it now, even if gethostname() changed since
622
+ # a holder this host can see is stale when its pid is dead, or when the process with
623
+ # that pid started after the lock was written (G4: a pid reused after a reboot); its
624
+ # start time unknown, a lock under 10 x LOCK_STALE_S stays (R2-3: a long sites.write).
625
+ # No readable pid, or another host's: the file's age decides
626
+ try:
627
+ pid_s, ts_s, *rest = content.split() # gethostname() never holds a space
628
+ pid, ts = int(pid_s), float(ts_s)
629
+ born = float(rest[1]) if len(rest) > 1 else 0 # 0: an older token or unknown
630
+ age = time.time() - ts
631
+ local = not rest or rest[0] == socket.gethostname()
632
+ except ValueError:
633
+ local = False
634
+ if local and pid == os.getpid():
635
+ pass # this process's own leftover: not in _HELD (checked above), so stale
636
+ elif local and _pid_alive(pid):
637
+ started = _pid_started(pid)
638
+ known = bool(born) and started is not None
639
+ if known and abs(started - born) <= _BORN_TOL_S:
640
+ return False # the holder itself, whatever the clock did since the take
641
+ if known and _FIXED_START:
642
+ pass # another start time on a fixed clock: a reused pid, so stale
643
+ elif (started <= ts + 5 if started is not None # 5 s of clock slack
644
+ else age <= 10 * LOCK_STALE_S):
645
+ return False
646
+ elif not local and age <= LOCK_STALE_S:
647
+ return False
648
+ # shortcut: a second stealer could race between this read and unlink; the window is
649
+ # tiny and only opens after a crash. Upgrade to rename-then-verify if it ever bites.
650
+ try:
651
+ if path.read_text(encoding="utf-8", errors="replace") == content:
652
+ path.unlink()
653
+ log.warning("stole a stale vault lock (%s)", content)
654
+ except OSError:
655
+ pass
656
+ return True
657
+
658
+ def _release_file(self) -> None:
659
+ self._drop(self._lock_path, self._token)
660
+
661
+ @staticmethod
662
+ def _drop(path: Path, token: str) -> None:
663
+ _HELD.discard(token) # a file left behind is now a leftover this process may steal
664
+ for attempt in range(REPLACE_TRIES):
665
+ try:
666
+ if path.read_text(encoding="utf-8", errors="replace") == token:
667
+ path.unlink()
668
+ return
669
+ except FileNotFoundError:
670
+ return
671
+ except OSError: # Windows: another process is reading the file; it lets go soon
672
+ time.sleep(0.01 * (attempt + 1))
673
+
674
+ # ---- writing --------------------------------------------------------------
675
+
676
+ def _atomic_write(self, path: Path, text: str | bytes,
677
+ expect: os.stat_result | None = None) -> bool:
678
+ """Temp file + os.replace with retry. Returns False if the file changed since `expect`."""
679
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
680
+ try:
681
+ with os.fdopen(fd, "wb") as f:
682
+ f.write(text if isinstance(text, bytes) else text.encode("utf-8"))
683
+ f.flush()
684
+ os.fsync(f.fileno())
685
+ if expect is not None:
686
+ st = path.stat()
687
+ if (st.st_mtime_ns, st.st_size) != (expect.st_mtime_ns, expect.st_size):
688
+ os.unlink(tmp)
689
+ return False
690
+ for attempt in range(REPLACE_TRIES):
691
+ try:
692
+ os.replace(tmp, path)
693
+ self._track(path)
694
+ return True
695
+ except PermissionError:
696
+ if attempt == REPLACE_TRIES - 1:
697
+ raise VaultError("vault_locked", f"{path.name} is open in another "
698
+ "program; try again.") from None
699
+ time.sleep(0.05 * 2**attempt)
700
+ except BaseException:
701
+ if os.path.exists(tmp):
702
+ os.unlink(tmp)
703
+ raise
704
+ return True # unreachable
705
+
706
+ def _mutate(self, path: Path, change: Callable[[str], str]) -> bool:
707
+ """Lock, read, apply `change`, write; reread and reapply if the file changed meanwhile."""
708
+ with self.lock():
709
+ for _ in range(5):
710
+ try:
711
+ st = path.stat()
712
+ text = path.read_bytes().decode("utf-8")
713
+ except FileNotFoundError:
714
+ raise VaultError("unknown_id", f"{path.name} does not exist; check the "
715
+ "id with find.") from None
716
+ new = change(text)
717
+ if new == text:
718
+ return False
719
+ if self._atomic_write(path, new, expect=st):
720
+ return True
721
+ log.info("%s changed during the edit; rereading", path)
722
+ raise VaultError("vault_locked", f"{path.name} keeps changing; try again.")
723
+
724
+ def _edit_fields(self, kind: str, id: str, values: dict) -> None:
725
+ def change(text: str) -> str:
726
+ parts = _split(text)
727
+ if parts is None:
728
+ raise VaultError("invalid_argument", f"{id} has no frontmatter.")
729
+ head, fm, close, body = parts
730
+ data = _load_fm(fm)
731
+ for k, v in values.items():
732
+ if v is None:
733
+ data.pop(k, None)
734
+ else:
735
+ data[k] = _to_yaml(v)
736
+ return head + _dump_fm(data, _newline(text)) + close + body
737
+
738
+ self._mutate(self.path_for(kind, id), change)
739
+
740
+ def set_field(self, kind: str, id: str, field: str, value) -> None:
741
+ if field in TOOL_PROPS or field == "merged_into":
742
+ raise VaultError("invalid_argument", f"'{field}' is computed by Keepfold and cannot "
743
+ "be set by hand.")
744
+ if field not in SET_FIELD_WHITELIST.get(kind, set()):
745
+ allowed = sorted(SET_FIELD_WHITELIST.get(kind, set()))
746
+ raise VaultError("invalid_argument", f"'{field}' cannot be set on a {kind}; "
747
+ f"settable fields: {', '.join(allowed)}.")
748
+ if isinstance(value, bool) or not isinstance(value, (str, int, float)):
749
+ raise VaultError("invalid_argument", "The value must be a string or a number.")
750
+ allowed_values = ENUMS.get((kind, field))
751
+ if allowed_values and value not in allowed_values:
752
+ raise VaultError("invalid_argument", f"{field} must be one of "
753
+ f"{', '.join(sorted(allowed_values))}.")
754
+ if (kind, field) == ("assessment", "date"):
755
+ check_day(field, value)
756
+ scan_secrets(str(value))
757
+ self._edit_fields(kind, id, {field: value})
758
+
759
+ def set_tool_props(self, kind: str, id: str, status: str, next_date: str | None) -> None:
760
+ """Write keepfold_status and keepfold_next; a None next_date removes keepfold_next."""
761
+ self._edit_fields(kind, id, {"keepfold_status": status, "keepfold_next": next_date})
762
+
763
+ def append_to_section(self, kind: str, id: str, heading: str, text: str) -> None:
764
+ scan_secrets(text)
765
+
766
+ def change(full: str) -> str:
767
+ parts = _split(full)
768
+ prefix = "".join(parts[:3]) if parts else ""
769
+ body = parts[3] if parts else full
770
+ nl = _newline(full)
771
+ lines = body.splitlines(keepends=True)
772
+ start, end = _section(lines, heading)
773
+ at = start
774
+ for j in range(end - 1, start - 1, -1):
775
+ if lines[j].strip():
776
+ at = j + 1
777
+ break
778
+ if at > 0 and not lines[at - 1].endswith("\n"):
779
+ lines[at - 1] += nl
780
+ new = text.replace("\r\n", "\n").rstrip("\n").replace("\n", nl) + nl
781
+ if at < len(lines) and HEADING_RE.match(lines[at].rstrip("\r\n")):
782
+ new += nl # keep a blank line before the next heading
783
+ lines.insert(at, new)
784
+ return prefix + "".join(lines)
785
+
786
+ self._mutate(self.path_for(kind, id), change)
787
+
788
+ def check_item(self, kind: str, id: str, section: str, item_text: str) -> bool:
789
+ """Tick the one unchecked item in `section` containing `item_text`.
790
+
791
+ Returns False if it was already ticked; raises invalid_argument if none or several match.
792
+ """
793
+ changed = False
794
+
795
+ def change(full: str) -> str:
796
+ nonlocal changed
797
+ parts = _split(full)
798
+ prefix = "".join(parts[:3]) if parts else ""
799
+ lines = (parts[3] if parts else full).splitlines(keepends=True)
800
+ start, end = _section(lines, section)
801
+ hits = [i for i in range(start, end)
802
+ if UNCHECKED_RE.match(lines[i]) and item_text in lines[i]]
803
+ if len(hits) > 1:
804
+ raise VaultError("invalid_argument", f"{len(hits)} items in '{section}' match; "
805
+ "give more of the item text.")
806
+ if not hits:
807
+ if any(CHECKED_RE.match(lines[i]) and item_text in lines[i]
808
+ for i in range(start, end)):
809
+ changed = False
810
+ return full
811
+ raise VaultError("invalid_argument", f"No unchecked item in '{section}' "
812
+ "matches; check the item text.")
813
+ lines[hits[0]] = lines[hits[0]].replace("[ ]", "[x]", 1)
814
+ changed = True
815
+ return prefix + "".join(lines)
816
+
817
+ self._mutate(self.path_for(kind, id), change)
818
+ return changed
819
+
820
+ def create_note(self, kind: str, id: str, fields: dict, body: str,
821
+ folder: str | None = None) -> Path:
822
+ """A new page in its kind's folder, or in `folder`, one of Vault.dirs(kind)."""
823
+ path = self.path_for(kind, id)
824
+ if folder is not None:
825
+ if folder not in self.dirs(kind):
826
+ raise VaultError("invalid_argument", f"A {kind} page cannot go in {folder}/.")
827
+ if not path.exists():
828
+ path = self._contained(self.root / folder / f"{id}.md")
829
+ if fields.get("id", id) != id:
830
+ raise VaultError("invalid_argument", "fields.id must match the note id.")
831
+ data = CommentedMap((k, _to_yaml(v)) for k, v in {"id": id, **fields}.items())
832
+ if body and not body.endswith("\n"):
833
+ body += "\n"
834
+ text = "---\n" + _dump_fm(data, "\n") + "---\n" + body
835
+ scan_secrets(text)
836
+ with self.lock():
837
+ if path.exists():
838
+ raise VaultError("invalid_argument", f"{kind} '{id}' already exists; patch it "
839
+ "instead.")
840
+ # ids are unique across kinds: the index keys nodes by id alone
841
+ other = next((k for k in self.KIND_DIRS for d in self.dirs(k)
842
+ if (self.root / d / f"{id}.md").is_file()), None)
843
+ if other:
844
+ title = fields.get("title") or id
845
+ raise VaultError("invalid_id", f"The id '{id}' is already the {other} "
846
+ f"'{id}', and ids are unique across kinds (force does not "
847
+ f"override this); use that note or choose another title, "
848
+ f"such as '{title} {kind}' (id {id}-{kind}).", [id])
849
+ path.parent.mkdir(parents=True, exist_ok=True)
850
+ self._atomic_write(path, text)
851
+ return path
852
+
853
+ def append_journal(self, day: str, hhmm: str, text: str) -> None:
854
+ """Add `- HH:MM text` under ## Log of the journal page for `day`, creating it if missing."""
855
+ text = " ".join(text.split())
856
+ scan_secrets(text)
857
+ from keepfold.relink import journal_up # lazy: relink imports this module
858
+
859
+ with self.lock():
860
+ if not self.path_for("journal", day).is_file():
861
+ up = journal_up(self, day) # Obsidian's graph: day -> month -> topic map
862
+ self.create_note("journal", day, {"title": f"Journal {day}", "kind": "journal",
863
+ "date": day},
864
+ (f"Up: [[{up}]]\n\n" if up else "") + "## Log\n")
865
+ self.append_to_section("journal", day, "Log", f"- {hhmm} {text}")
866
+
867
+ def append_log(self, day: str, type: str, title: str) -> None:
868
+ """Add `## [day] type | title` to log.md; earlier lines are never touched."""
869
+ line = f"## [{day}] {type} | {' '.join(str(title).split())}\n"
870
+ path = self.root / "log.md"
871
+ with self.lock():
872
+ old = path.read_bytes().decode("utf-8") if path.is_file() else "# Log\n\n"
873
+ self.write_text(path, old + line)
874
+
875
+ def remove(self, path: Path) -> bool:
876
+ """Delete one vault file under the lock, retrying a Windows sharing error. False if it
877
+ was not there."""
878
+ p = self._contained(path)
879
+ with self.lock():
880
+ _PARSED.pop(p, None)
881
+ for attempt in range(REPLACE_TRIES):
882
+ try:
883
+ p.unlink()
884
+ self._track(p)
885
+ return True
886
+ except FileNotFoundError:
887
+ return False
888
+ except PermissionError:
889
+ if attempt == REPLACE_TRIES - 1:
890
+ raise VaultError("vault_locked", f"{path.name} is open in another "
891
+ "program; try again.") from None
892
+ time.sleep(0.05 * 2**attempt)
893
+ return False # unreachable
894
+
895
+ def move(self, src: Path, dst: Path) -> None:
896
+ """Move one vault file under the lock: `dst` written atomically with `src`'s bytes and
897
+ mtime, then `src` removed. A crash between leaves the same bytes in both, and a rerun
898
+ finishes; VaultError when `dst` already holds something else."""
899
+ src, dst = self._contained(src), self._contained(dst)
900
+ with self.lock():
901
+ st, data = src.stat(), src.read_bytes()
902
+ if dst.exists() and dst.read_bytes() != data:
903
+ raise VaultError("invalid_argument", f"{dst.name} is already in "
904
+ f"{dst.parent.relative_to(self.root).as_posix()}/.")
905
+ dst.parent.mkdir(parents=True, exist_ok=True)
906
+ self._atomic_write(dst, data)
907
+ os.utime(dst, ns=(st.st_atime_ns, st.st_mtime_ns)) # pages keep their dates
908
+ self.remove(src)
909
+
910
+ def update_text(self, path: Path, change: Callable[[str], str], default: str = "") -> bool:
911
+ """Read-modify-write a page the owner may edit at the same time (B13): `change` (which
912
+ may run more than once) gets the text, or `default` if the file is missing, and an
913
+ outside edit made meanwhile is reread instead of overwritten. False: nothing changed."""
914
+ p = self._contained(path)
915
+
916
+ def scanned(text: str) -> str:
917
+ new = change(text)
918
+ if new != text:
919
+ scan_secrets(new)
920
+ return new
921
+
922
+ with self.lock():
923
+ if p.is_file():
924
+ return self._mutate(p, scanned)
925
+ new = scanned(default)
926
+ if new == default:
927
+ return False
928
+ p.parent.mkdir(parents=True, exist_ok=True)
929
+ self._atomic_write(p, new)
930
+ return True
931
+
932
+ def write_text(self, path: Path, text: str) -> Path:
933
+ """Atomic write for generated files (Today.md, session notes, dashboard). Files under
934
+ `.keepfold/` are git-ignored local caches and views, never committed, so they skip the
935
+ secret scan (scanning an 18.8 MB dashboard took ~10 s at 5k pages)."""
936
+ p = self._contained(path)
937
+ if not p.is_relative_to(self.root / ".keepfold"):
938
+ scan_secrets(text)
939
+ with self.lock():
940
+ p.parent.mkdir(parents=True, exist_ok=True)
941
+ self._atomic_write(p, text)
942
+ return p