coldmemory 0.3.6__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.
coldmemory/ingest.py ADDED
@@ -0,0 +1,742 @@
1
+ """Read Obsidian vaults, Notion Markdown exports and git repo docs into one scrubbed, linked corpus."""
2
+
3
+ import errno
4
+ import hashlib
5
+ import json
6
+ import multiprocessing
7
+ import os
8
+ import pickle
9
+ import posixpath
10
+ import re
11
+ import stat
12
+ import subprocess
13
+ import time
14
+ from collections import Counter, defaultdict
15
+ from concurrent.futures import ProcessPoolExecutor
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from urllib.parse import unquote
19
+
20
+ from . import redact
21
+ from .redact import scrub
22
+
23
+ KINDS = ("obsidian", "notion", "repo")
24
+ SUFFIXES = (".md", ".markdown", ".mdx", ".rst", ".txt")
25
+ SKIP_DIRS = {"node_modules", "vendor", "dist", "build", "__pycache__"}
26
+ MAX_BYTES = 1 << 20
27
+ PARALLEL_READS = 512
28
+ PARSER = hashlib.sha256(Path(__file__).read_bytes() + Path(redact.__file__).read_bytes()).hexdigest()
29
+ STALE = {"superseded", "deprecated", "obsolete", "archived", "rejected", "replaced", "reversed"}
30
+
31
+ _FENCE = re.compile(r"^([`~]{3,}).*?^\1[^\n]*$|`[^`\n]+`", re.S | re.M)
32
+ _WIKI = re.compile(r"!?\[\[([^\]|#\n]*)(?:#[^\]|\n]*)?(?:\|[^\]\n]*)?\]\]")
33
+ _MDLINK = re.compile(r"\[[^\]\n]*\]\(<?([^)\s>]+)>?(?:\s+\"[^\"]*\")?\)")
34
+ _TAG = re.compile(r"(?<![\w/#&])#([A-Za-z][\w/-]*)")
35
+ _HEADING = re.compile(r"^#{1,6}\s+(.+?)\s*#*$")
36
+ _PROPERTY = re.compile(r"^[-*]?\s*\*{0,2}([A-Z][\w ]{0,30}?)\*{0,2}:\*{0,2}\s+(.+)$")
37
+ _REPLACES = re.compile(
38
+ r"^(?:[^\S\n]|[>*_#-])*+(?:\[![\w-]+\][+-]?)?(?:[^\S\n]|[>*_-])*+(?:status(?:[^\S\n]|\*)*+:(?:[^\S\n]|\*)*+)?"
39
+ r"(superseded by|replaced by|supersedes|replaces)\b(.*)$", re.I | re.M)
40
+ _NOTION_ID = re.compile(r"\s+[0-9a-f]{32}$")
41
+ _DECISION = re.compile(r"^(?:\d+[.)]\s*)?(?:decision|outcome|resolution)\b", re.I)
42
+ _MONTHS = ("january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
43
+ "november", "december")
44
+ _ISO_DATE = re.compile(r"(?<!\d)(19[89]\d|20[0-3]\d)(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[12]\d|3[01]))?)?(?!\d)")
45
+ _NAMED_DATE = re.compile(rf"\b({'|'.join(_MONTHS)})\s+(\d{{1,2}}),?\s+(19[89]\d|20[0-3]\d)\b", re.I)
46
+ DATE_KEYS = ("effective", "decided", "date", "created", "created_time", "created time", "updated", "modified",
47
+ "last_edited", "last_edited_time", "last edited time")
48
+
49
+
50
+ class Refused(ValueError):
51
+ """The path is outside what ColdMemory is allowed to read."""
52
+
53
+
54
+ class StaleNoteRead(RuntimeError):
55
+ """A lazily-loaded note disappeared or shrank on disk before verification finished."""
56
+
57
+ def __init__(self, key):
58
+ super().__init__(key)
59
+ self.key = key
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class Source:
64
+ kind: str
65
+ label: str
66
+ root: str
67
+
68
+
69
+ @dataclass
70
+ class Note:
71
+ key: str
72
+ source: Source
73
+ rel: str
74
+ sha256: str
75
+ signature: tuple
76
+ lines: list
77
+ title: str
78
+ body_start: int
79
+ sections: list
80
+ tags: list
81
+ aliases: list
82
+ status: str
83
+ raw_links: list
84
+ raw_newer: list
85
+ raw_older: list
86
+ links: list = field(default_factory=list)
87
+ backlinks: list = field(default_factory=list)
88
+ superseded_by: list = field(default_factory=list)
89
+ dangling: int = 0
90
+ date: str = ""
91
+
92
+ @property
93
+ def path(self):
94
+ return f"{self.source.root}/{self.rel}"
95
+
96
+ @property
97
+ def stale(self):
98
+ return bool(self.superseded_by or self.raw_newer) or self.status in STALE
99
+
100
+ @property
101
+ def line_count(self):
102
+ return len(self.lines)
103
+
104
+
105
+ def parse_source(spec):
106
+ kind, _, path = spec.partition(":")
107
+ if kind not in KINDS or not path:
108
+ raise ValueError(f"source must look like kind:/path, where kind is one of {', '.join(KINDS)}")
109
+ root = Path(path).expanduser().resolve(strict=True)
110
+ if not root.is_dir():
111
+ raise ValueError("source is not a directory")
112
+ return Source(kind, root.name, str(root))
113
+
114
+
115
+ def check_rel(rel):
116
+ parts = rel.split("/")
117
+ if any(not p or p.startswith(".") or "\\" in p or not p.isprintable() for p in parts):
118
+ raise Refused("hidden, absolute or parent paths are not allowed")
119
+ if set(parts[:-1]) & SKIP_DIRS or not rel.lower().endswith(SUFFIXES):
120
+ raise Refused("not a supported document")
121
+ if scrub(rel) != rel:
122
+ raise Refused("the file name looks like a secret")
123
+ return parts
124
+
125
+
126
+ def read_bytes(root, rel):
127
+ """Open each path component without following symlinks, so a swapped directory cannot redirect the read."""
128
+ parts = check_rel(rel)
129
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
130
+ try:
131
+ parent = os.open(root, flags)
132
+ try:
133
+ for part in parts[:-1]:
134
+ child = os.open(part, flags, dir_fd=parent)
135
+ os.close(parent)
136
+ parent = child
137
+ handle = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
138
+ finally:
139
+ os.close(parent)
140
+ except OSError as error:
141
+ if error.errno in (errno.ELOOP, errno.ENOTDIR):
142
+ raise Refused("symlinks are not followed") from None
143
+ raise
144
+ with os.fdopen(handle, "rb") as stream:
145
+ info = os.fstat(stream.fileno())
146
+ if not stat.S_ISREG(info.st_mode):
147
+ raise Refused("not a regular file")
148
+ data = stream.read(MAX_BYTES + 1)
149
+ if len(data) > MAX_BYTES:
150
+ raise Refused("file is larger than 1 MiB")
151
+ return data, _signature(info)
152
+
153
+
154
+ def _signature(info):
155
+ return info.st_mtime_ns, info.st_ctime_ns, info.st_size, info.st_ino
156
+
157
+
158
+ def _state(path):
159
+ try:
160
+ return _signature(os.lstat(path))
161
+ except FileNotFoundError:
162
+ return None
163
+
164
+
165
+ def _candidates(source):
166
+ if source.kind == "repo":
167
+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
168
+ done = subprocess.run(["git", "-c", "core.fsmonitor=false", "-C", source.root, "ls-files", "-z"],
169
+ capture_output=True, env=env)
170
+ if done.returncode:
171
+ raise ValueError(f"git could not list the files of repo source {source.label}")
172
+ yield from sorted(set(done.stdout.decode("utf-8", "surrogateescape").split("\0")) - {""})
173
+ return
174
+ for folder, names, files in os.walk(source.root, onerror=_raise):
175
+ names[:] = sorted(n for n in names if not n.startswith(".") and n not in SKIP_DIRS)
176
+ base = os.path.relpath(folder, source.root).replace(os.sep, "/")
177
+ prefix = "" if base == "." else f"{base}/"
178
+ for name in sorted(files):
179
+ yield prefix + name
180
+
181
+
182
+ def _raise(error):
183
+ raise error
184
+
185
+
186
+ def _scalar(value):
187
+ return value.strip().strip("\"'")
188
+
189
+
190
+ def _items(value):
191
+ return [_scalar(v) for v in value.strip().strip("[]").split(",") if _scalar(v)]
192
+
193
+
194
+ def frontmatter(lines):
195
+ """Parse `key: value`, `[a, b]` and `- item` lists. Anything more complex is ignored."""
196
+ if not lines or lines[0].strip() != "---":
197
+ return {}, 0
198
+ meta, key = {}, None
199
+ for number, line in enumerate(lines[1:], 1):
200
+ if line.strip() in ("---", "..."):
201
+ return meta, number + 1
202
+ item = re.match(r"^\s*-\s+(.+)$", line)
203
+ pair = re.match(r"^([\w -]+):\s*(.*)$", line)
204
+ if item and key:
205
+ meta[key] = [*meta[key], _scalar(item[1])]
206
+ elif pair:
207
+ key, value = pair[1].strip().lower().replace("-", "_").replace(" ", "_"), pair[2].strip()
208
+ if value.startswith("[["):
209
+ meta[key] = [value]
210
+ else:
211
+ meta[key] = _items(value) if value.startswith("[") else [_scalar(value)] if value else []
212
+ return {}, 0
213
+
214
+
215
+ def note_date(text):
216
+ """Return the first date in text as YYYY, YYYY-MM or YYYY-MM-DD, or ""."""
217
+ named = _NAMED_DATE.search(text)
218
+ if named:
219
+ return f"{named[3]}-{_MONTHS.index(named[1].lower()) + 1:02d}-{int(named[2]):02d}"
220
+ found = _ISO_DATE.search(text)
221
+ return "-".join(part for part in found.groups() if part) if found else ""
222
+
223
+
224
+ def _targets(text):
225
+ wiki = [("wiki", t.strip()) for t in _WIKI.findall(text) if t.strip()]
226
+ return wiki + [("path", unquote(t)) for t in _MDLINK.findall(text)
227
+ if "://" not in t and not t.startswith(("#", "mailto:", "/"))]
228
+
229
+
230
+ def _named(values):
231
+ return [target for value in values for target in (_targets(value) or [("wiki", value)])]
232
+
233
+
234
+ def _mask(match):
235
+ code = match.group()
236
+ return "\n" * code.count("\n") if "\n" in code else " " * len(code)
237
+
238
+
239
+ def parse_note(source, rel, data, signature):
240
+ text = scrub(data.decode("utf-8-sig", "replace").replace("\r\n", "\n"))
241
+ lines = text.split("\n")
242
+ meta, start = frontmatter(lines)
243
+ masked = _FENCE.sub(_mask, "\n".join(lines[start:]))
244
+ visible = [""] * start + masked.split("\n")
245
+
246
+ headings = [(n, m[1]) for n, line in enumerate(visible) if (m := _HEADING.match(line))]
247
+ stem = _NOTION_ID.sub("", posixpath.splitext(posixpath.basename(rel))[0])
248
+ title = (meta.get("title") or [headings[0][1] if headings else stem])[0]
249
+
250
+ body_start = headings[0][0] + 1 if headings else start
251
+ properties = {}
252
+ for number in range(body_start, len(lines)):
253
+ pair = _PROPERTY.match(visible[number])
254
+ if pair:
255
+ properties[pair[1].lower()] = pair[2]
256
+ elif visible[number].strip():
257
+ break
258
+ elif properties:
259
+ break
260
+ if properties:
261
+ body_start = number
262
+
263
+ bounds = [(start, title)] + [h for h in headings if h[0] > start]
264
+ sections = [(begin, heading, end) for (begin, heading), end
265
+ in zip(bounds, [b[0] for b in bounds[1:]] + [len(lines)])
266
+ if any(line.strip() for line in lines[begin:end])]
267
+
268
+ status = " ".join(meta.get("status", [])) or properties.get("status", "")
269
+ if not status:
270
+ for begin, heading, end in sections:
271
+ if heading.lower() == "status":
272
+ status = next((line for line in visible[begin + 1:end] if line.strip()), "")
273
+ status = (re.findall(r"[a-z]+", status.lower()) or [""])[0]
274
+
275
+ newer, older = _named(meta.get("superseded_by", [])), _named(meta.get("supersedes", []))
276
+ for relation, rest in _REPLACES.findall(masked):
277
+ (newer if relation.lower().endswith("by") else older).extend(_targets(rest))
278
+ dated = [value for key in DATE_KEYS for value in [*meta.get(key, []), properties.get(key, "")]]
279
+ date = next(filter(None, map(note_date, [*dated, title, stem])), "")
280
+ tags = [t.lstrip("#") for t in meta.get("tags", [])] + _items(properties.get("tags", "")) + _TAG.findall(masked)
281
+
282
+ return Note(
283
+ key=f"{source.label}/{rel}", source=source, rel=rel, sha256=hashlib.sha256(data).hexdigest(),
284
+ signature=signature, lines=lines, title=title, body_start=body_start, sections=sections,
285
+ tags=sorted({t.lower() for t in tags}), aliases=meta.get("aliases", []), status=status,
286
+ raw_links=_targets(masked), raw_newer=newer, raw_older=older, date=date)
287
+
288
+
289
+ def _read_or_refusal(item):
290
+ try:
291
+ return Corpus.read(*item)
292
+ except (Refused, FileNotFoundError) as error:
293
+ return error
294
+
295
+
296
+ def _cache_file(sources):
297
+ folder = os.environ.get("COLDMEMORY_NOTE_CACHE")
298
+ if not folder:
299
+ return None
300
+ named = json.dumps([PARSER, sorted((s.kind, s.label, s.root) for s in sources)]).encode()
301
+ return Path(folder) / f"notes-{hashlib.sha256(named).hexdigest()[:32]}.pickle"
302
+
303
+
304
+ def _load_cache(path):
305
+ """Parsed notes from an earlier run. Only an owner-only regular file is trusted, checked on the opened file."""
306
+ try:
307
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
308
+ except FileNotFoundError:
309
+ return {}
310
+ except OSError as error:
311
+ raise Refused("the note cache must be an owner-only regular file") from error
312
+ with open(fd, "rb") as stream:
313
+ info = os.fstat(fd)
314
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
315
+ raise Refused("the note cache must be an owner-only regular file")
316
+ return pickle.load(stream)
317
+
318
+
319
+ def _save_cache(path, notes):
320
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
321
+ temp = path.with_name(f".{path.name}.{os.getpid()}")
322
+ with open(os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), "wb") as stream:
323
+ pickle.dump(notes, stream, protocol=pickle.HIGHEST_PROTOCOL)
324
+ os.replace(temp, path)
325
+
326
+
327
+ class Corpus:
328
+ """The live notes of one bundle. refresh() re-reads only files whose stat changed, then relinks.
329
+
330
+ With COLDMEMORY_NOTE_CACHE set, parsed notes persist there between processes, keyed by path and stat, in a file
331
+ named for the sources and the parser code. A walk that reads PARALLEL_READS files or more rewrites it.
332
+ With COLDMEMORY_WALK_SECONDS set, refresh() walks the sources at most that often; forget() forces the next walk,
333
+ and so does a query that reaches a removed note whose file is back."""
334
+
335
+ def __init__(self, sources, pinned=None, *, load_cache=True):
336
+ if not sources:
337
+ raise ValueError("at least one source is required")
338
+ if len({s.label for s in sources}) != len(sources):
339
+ raise ValueError("two sources have the same folder name")
340
+ self.pinned = pinned
341
+ self.sources = sources
342
+ self.notes = {}
343
+ self.skipped = Counter()
344
+ self.cache = _cache_file(sources) if load_cache else None
345
+ self._cache_loaded = load_cache != "lazy"
346
+ self.parsed = _load_cache(self.cache) if (self.cache and self._cache_loaded) else {}
347
+ self.walked = None
348
+ self.walked_wall = None
349
+ self.allowed = set()
350
+ self.gone, self.reached = {}, set()
351
+ self._disk_index = None
352
+ self._removed = set()
353
+ self._overrides = {}
354
+ self._forgotten = set()
355
+ self._resolved_edges = None
356
+ self._verified_sigs = {}
357
+ self._generation = 0
358
+
359
+ def attach_disk_index(self, disk_index, *, walked=None, walked_wall=None, skipped=None):
360
+ """Back this Corpus with a verified DiskIndex instead of holding all Note objects in RAM."""
361
+ from .disk_index import DiskNotesView
362
+
363
+ self._disk_index = disk_index
364
+ self._removed = set()
365
+ self._overrides = {}
366
+ self._forgotten = set()
367
+ self._resolved_edges = None
368
+ self._verified_sigs = {}
369
+ self.parsed = {}
370
+ self.allowed = set()
371
+ self.notes = DiskNotesView(disk_index, self._removed, self._overrides)
372
+ self.gone = disk_index.load_gone()
373
+ self.reached &= self.gone.keys()
374
+ if walked is not None:
375
+ self.walked = walked
376
+ if walked_wall is not None:
377
+ self.walked_wall = walked_wall
378
+ elif walked is not None:
379
+ self.walked_wall = disk_index.walked_at
380
+ if skipped is not None:
381
+ self.skipped = Counter(skipped)
382
+ self._generation += 1
383
+
384
+ def has_unindexed_changes(self):
385
+ """True when live notes include additions or edits not yet present in the attached DiskIndex."""
386
+ return self._disk_index is None or bool(self._overrides)
387
+
388
+ def forget(self, key):
389
+ if self._disk_index is not None:
390
+ self._forgotten.add(key)
391
+ self._verified_sigs.pop(key, None)
392
+ if key in self._overrides:
393
+ self._overrides[key].signature = None
394
+ self._disk_index.invalidate_lines(key)
395
+ else:
396
+ self.notes[key].signature = None
397
+ self.walked = None
398
+
399
+ def has(self, key):
400
+ """True for a live note. A removed note's key is remembered so returned() can look for its file."""
401
+ if key in self.notes:
402
+ return True
403
+ if key in self.gone:
404
+ self.reached.add(key)
405
+ return False
406
+
407
+ def returned(self):
408
+ """True when the file of a removed note a query reached changed since the last walk; the next refresh then walks.
409
+ A note dropped from a repo index while its file stays is seen at the next timed walk."""
410
+ if any(_state(path) != state for path, state in map(self.gone.get, self.reached)):
411
+ self.walked = None
412
+ return True
413
+ return False
414
+
415
+ def refresh(self):
416
+ within = float(os.environ.get("COLDMEMORY_WALK_SECONDS") or 0)
417
+ started = time.monotonic()
418
+ started_wall = time.time()
419
+ if self.walked is not None and started - self.walked < within:
420
+ return False
421
+ if self._disk_index is not None:
422
+ return self._refresh_disk(started, started_wall)
423
+ if self.cache and not self._cache_loaded:
424
+ self.parsed = _load_cache(self.cache)
425
+ self._cache_loaded = True
426
+ order, parsed, todo, skipped, seen = [], {}, [], Counter(), set()
427
+ for source in self.sources:
428
+ for rel in _candidates(source):
429
+ key = f"{source.label}/{rel}"
430
+ if self.pinned is not None and key not in self.pinned:
431
+ continue
432
+ if not rel.lower().endswith(SUFFIXES):
433
+ continue
434
+ seen.add(key)
435
+ try:
436
+ if rel not in self.allowed:
437
+ check_rel(rel)
438
+ self.allowed.add(rel)
439
+ info = os.lstat(os.path.join(source.root, rel))
440
+ except Refused as reason:
441
+ skipped[str(reason)] += 1
442
+ continue
443
+ except FileNotFoundError:
444
+ seen.discard(key)
445
+ continue
446
+ order.append(key)
447
+ old = self.notes.get(key) or self.parsed.get(key)
448
+ if old and old.signature == _signature(info) and stat.S_ISREG(info.st_mode):
449
+ parsed[key] = old
450
+ else:
451
+ todo.append((source, rel))
452
+ for (source, rel), note in zip(todo, self._read_all(todo)):
453
+ if isinstance(note, Refused):
454
+ skipped[str(note)] += 1
455
+ elif isinstance(note, Note):
456
+ parsed[f"{source.label}/{rel}"] = note
457
+ fresh = {k: parsed[k] for k in order if k in parsed
458
+ and (self.pinned is None or parsed[k].sha256 == self.pinned[k]["sha256"])}
459
+ changed = fresh.keys() != self.notes.keys() or any(fresh[k] is not self.notes[k] for k in fresh)
460
+ if self.cache and len(todo) >= PARALLEL_READS:
461
+ _save_cache(self.cache, parsed)
462
+ gone = {**{k: path for k, (path, _) in self.gone.items()},
463
+ **{k: os.path.join(n.source.root, n.rel) for k, n in self.notes.items()}}
464
+ self.gone = {k: (path, _state(path)) for k, path in gone.items() if k not in seen}
465
+ self.reached &= self.gone.keys()
466
+ self.notes, self.skipped, self.parsed, self.walked, self.walked_wall = fresh, skipped, parsed, started, started_wall
467
+ if changed:
468
+ self._link()
469
+ self._generation += 1
470
+ return changed
471
+
472
+ def _refresh_disk(self, started, started_wall):
473
+ """Low-memory refresh against an attached DiskIndex: reads only changed/new/forgotten files."""
474
+ from .disk_index import DiskNotesView
475
+
476
+ candidates, skipped, seen = [], Counter(), set()
477
+ for source in self.sources:
478
+ for rel in _candidates(source):
479
+ key = f"{source.label}/{rel}"
480
+ if self.pinned is not None and key not in self.pinned:
481
+ continue
482
+ if not rel.lower().endswith(SUFFIXES):
483
+ continue
484
+ seen.add(key)
485
+ try:
486
+ check_rel(rel)
487
+ info = os.lstat(os.path.join(source.root, rel))
488
+ except Refused as reason:
489
+ skipped[str(reason)] += 1
490
+ continue
491
+ except FileNotFoundError:
492
+ seen.discard(key)
493
+ continue
494
+ candidates.append((key, source, rel, info))
495
+
496
+ disk_sigs = self._disk_index.batch_signatures([c[0] for c in candidates])
497
+ live_from_disk = set()
498
+ new_overrides = {}
499
+ todo = []
500
+ for key, source, rel, info in candidates:
501
+ cur_sig = _signature(info)
502
+ is_reg = stat.S_ISREG(info.st_mode)
503
+ if key in self._forgotten:
504
+ todo.append((source, rel))
505
+ elif key in self._overrides:
506
+ old = self._overrides[key]
507
+ if old.signature == cur_sig and is_reg:
508
+ if self.pinned is None or old.sha256 == self.pinned[key]["sha256"]:
509
+ new_overrides[key] = old
510
+ else:
511
+ todo.append((source, rel))
512
+ elif key in disk_sigs:
513
+ disk_sig, disk_sha = disk_sigs[key]
514
+ if is_reg and (
515
+ disk_sig == cur_sig
516
+ or self._verified_sigs.get(key) == (cur_sig, disk_sha)
517
+ ):
518
+ if self.pinned is None or disk_sha == self.pinned[key]["sha256"]:
519
+ live_from_disk.add(key)
520
+ else:
521
+ todo.append((source, rel))
522
+ else:
523
+ todo.append((source, rel))
524
+
525
+ for (source, rel), note in zip(todo, self._read_all(todo)):
526
+ if isinstance(note, Refused):
527
+ skipped[str(note)] += 1
528
+ elif isinstance(note, Note):
529
+ key = f"{source.label}/{rel}"
530
+ if self.pinned is not None and note.sha256 != self.pinned[key]["sha256"]:
531
+ continue
532
+ if key in disk_sigs and disk_sigs[key][1] == note.sha256:
533
+ self._verified_sigs[key] = (note.signature, note.sha256)
534
+ live_from_disk.add(key)
535
+ else:
536
+ self._verified_sigs.pop(key, None)
537
+ new_overrides[key] = note
538
+ if self._verified_sigs:
539
+ self._verified_sigs = {k: v for k, v in self._verified_sigs.items() if k in live_from_disk}
540
+
541
+ live_all = live_from_disk | new_overrides.keys()
542
+ missing_disk = self._disk_index.missing_keys(live_all)
543
+ new_removed = set(missing_disk.keys())
544
+ changed = (
545
+ new_removed != self._removed
546
+ or new_overrides.keys() != self._overrides.keys()
547
+ or any(new_overrides[k] is not self._overrides[k] for k in new_overrides)
548
+ )
549
+ gone_paths = {k: path for k, (path, _) in self.gone.items() if k not in seen}
550
+ for k, path in missing_disk.items():
551
+ if k not in self._removed and k not in seen:
552
+ gone_paths[k] = path
553
+ for k, n in self._overrides.items():
554
+ if k not in seen:
555
+ gone_paths[k] = os.path.join(n.source.root, n.rel)
556
+ self.gone = {k: (path, _state(path)) for k, path in gone_paths.items()}
557
+ self.reached &= self.gone.keys()
558
+ self._removed = new_removed
559
+ self._overrides = new_overrides
560
+ self._forgotten.clear()
561
+ self.skipped = skipped
562
+ self.walked = started
563
+ self.walked_wall = started_wall
564
+ if changed or self._resolved_edges is None:
565
+ self._resolved_edges = self._disk_index.resolve_live_edges(
566
+ live_all, self._overrides, self._removed
567
+ )
568
+ self.notes = DiskNotesView(
569
+ self._disk_index, self._removed, self._overrides, *self._resolved_edges
570
+ )
571
+ if changed:
572
+ self._generation += 1
573
+ return changed
574
+
575
+ @staticmethod
576
+ def _read_all(todo):
577
+ if len(todo) < PARALLEL_READS:
578
+ return [_read_or_refusal(item) for item in todo]
579
+ workers = min(os.cpu_count() or 1, 32)
580
+ with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("forkserver")) as pool:
581
+ return list(pool.map(_read_or_refusal, todo, chunksize=max(1, len(todo) // (workers * 8))))
582
+
583
+ @staticmethod
584
+ def read(source, rel):
585
+ return parse_note(source, rel, *read_bytes(source.root, rel))
586
+
587
+ def _link(self):
588
+ local, everywhere = defaultdict(set), defaultdict(set)
589
+ for note in self.notes.values():
590
+ path = posixpath.splitext(note.rel)[0]
591
+ names = {path, posixpath.basename(path), _NOTION_ID.sub("", posixpath.basename(path)),
592
+ note.title, *note.aliases}
593
+ for name in names:
594
+ local[note.source.label, name.lower()].add(note.key)
595
+ everywhere[name.lower()].add(note.key)
596
+ note.links, note.backlinks, note.superseded_by, note.dangling = [], [], [], 0
597
+
598
+ def resolve(note, target):
599
+ kind, value = target
600
+ if kind == "path":
601
+ value = posixpath.normpath(posixpath.join(posixpath.dirname(note.rel), value.partition("#")[0]))
602
+ key = f"{note.source.label}/{value}"
603
+ return key if key in self.notes else None
604
+ name = value.lower().removesuffix(".md")
605
+ found = local[note.source.label, name]
606
+ if not found and len(everywhere[name]) == 1:
607
+ found = everywhere[name]
608
+ here = posixpath.dirname(note.key)
609
+ return min(found, key=lambda k: (posixpath.dirname(k) != here, k.count("/"), k), default=None)
610
+
611
+ for note in self.notes.values():
612
+ found = [resolve(note, t) for t in note.raw_links]
613
+ note.links = sorted({k for k in found if k and k != note.key})
614
+ note.dangling = found.count(None)
615
+ for note in self.notes.values():
616
+ for key in note.links:
617
+ self.notes[key].backlinks.append(note.key)
618
+ for key in filter(None, (resolve(note, t) for t in note.raw_newer)):
619
+ if key != note.key:
620
+ note.superseded_by.append(key)
621
+ for key in filter(None, (resolve(note, t) for t in note.raw_older)):
622
+ if key != note.key:
623
+ self.notes[key].superseded_by.append(note.key)
624
+ for note in self.notes.values():
625
+ note.superseded_by = sorted(set(note.superseded_by))
626
+
627
+ def current(self, key, checked=None, *, limit=None):
628
+ """Follow replacements to the newest notes. A cycle has no newest note, so it returns nothing."""
629
+ found, seen, queue = [], {key}, list(self.notes[key].superseded_by)
630
+ while queue:
631
+ if limit is not None and len(seen) >= limit:
632
+ break
633
+ item = queue.pop(0)
634
+ if item in seen:
635
+ continue
636
+ seen.add(item)
637
+ note = self.notes[item]
638
+ if note.superseded_by:
639
+ queue.extend(note.superseded_by)
640
+ elif not note.stale:
641
+ found.append(item)
642
+ if checked is not None:
643
+ checked.update(seen)
644
+ return found
645
+
646
+ def graph(self):
647
+ return {key: {"sha256": n.sha256, "mtime_ns": n.signature[0], "title": n.title, "tags": n.tags,
648
+ "status": n.status, "links": n.links, "backlinks": n.backlinks,
649
+ "superseded_by": n.superseded_by, "dangling": n.dangling}
650
+ for key, n in sorted(self.notes.items())}
651
+
652
+
653
+ def render_prompt(question):
654
+ """Training and serving must build the prompt the same way, so both call this."""
655
+ return f"### Memory question\n{question.strip()}\n\n### Memory answer\n"
656
+
657
+
658
+ def render_answer(text, keys):
659
+ return f"{text.strip()}\nSources: {'; '.join(keys)}"
660
+
661
+
662
+ def parse_answer(text):
663
+ body, _, tail = text.partition("\nSources:")
664
+ keys = [k.strip() for k in tail.strip().split("\n")[0].split(";") if k.strip()]
665
+ return " ".join(body.split()), list(dict.fromkeys(keys))
666
+
667
+
668
+ def sentences(text):
669
+ return [s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s]
670
+
671
+
672
+ def _paragraph(note, start, end):
673
+ block = []
674
+ for line in note.lines[start:end]:
675
+ if line.strip() and not _HEADING.match(line):
676
+ block.append(line.strip())
677
+ elif block:
678
+ break
679
+ chosen, words = [], 0
680
+ for sentence in sentences(" ".join(block)):
681
+ words += len(sentence.split())
682
+ if chosen and words > 120:
683
+ break
684
+ chosen.append(sentence)
685
+ return " ".join(chosen)
686
+
687
+
688
+ def decision_section(note):
689
+ return next((s for s in note.sections if _DECISION.match(s[1])), None)
690
+
691
+
692
+ def compile_dataset(corpus, approved=()):
693
+ """Return (train, val) rows. Each fact is trained on two wordings and checked on a third."""
694
+ notes = corpus.notes
695
+ repeats = Counter(n.title for n in notes.values())
696
+
697
+ def name(note):
698
+ return note.title if repeats[note.title] == 1 else f"{note.title} ({note.key})"
699
+
700
+ facts, tagged = [], defaultdict(list)
701
+ for key, note in sorted(notes.items()):
702
+ title = name(note)
703
+ if note.stale:
704
+ newer = corpus.current(key)
705
+ answer = f"No. {title} is out of date."
706
+ if newer:
707
+ answer += f" Use {'; '.join(name(notes[k]) for k in newer)}."
708
+ facts.append((f"stale:{key}", answer, [*newer, key],
709
+ [f"Is {title} still current?", f"Can I rely on {title}?", f"Is {title} out of date?"]))
710
+ continue
711
+ for tag in note.tags:
712
+ tagged[tag].append(key)
713
+ lead = _paragraph(note, note.body_start, len(note.lines))
714
+ if lead:
715
+ facts.append((f"about:{key}", lead, [key],
716
+ [f"What is {title}?", f"Summarize {title}.", f"Tell me about {title}."]))
717
+ section = decision_section(note)
718
+ decision = _paragraph(note, section[0] + 1, section[2]) if section else ""
719
+ if decision:
720
+ facts.append((f"decision:{key}", decision, [key],
721
+ [f"What did we decide in {title}?", f"What is the current decision in {title}?",
722
+ f"What was the outcome of {title}?"]))
723
+ related = [name(notes[k]) for k in sorted({*note.links, *note.backlinks}) if not notes[k].stale][:8]
724
+ facts.append((f"where:{key}", f"{title}." + (f" Related: {'; '.join(related)}." if related else ""), [key],
725
+ [f"Where is {title} documented?", f"Which file covers {title}?",
726
+ f"Where should I look for {title}?"]))
727
+ for tag, keys in sorted(tagged.items()):
728
+ facts.append((f"tag:{tag}", "; ".join(name(notes[k]) for k in keys[:10]) + ".", keys[:10],
729
+ [f"Which notes are tagged {tag}?", f"List the {tag} notes.", f"What notes cover {tag}?"]))
730
+ for entry in approved:
731
+ facts.append((f"approved:{entry['id']}", entry["decision"], [s["key"] for s in entry["sources"]],
732
+ [f"What did we decide about {entry['title']}?", f"What is our decision on {entry['title']}?",
733
+ f"What was agreed about {entry['title']}?"]))
734
+
735
+ train, val = [], []
736
+ for fact, answer, keys, questions in facts:
737
+ group = hashlib.sha256(fact.encode()).hexdigest()[:16]
738
+ text = scrub(render_answer(answer, keys))
739
+ for number, question in enumerate(questions):
740
+ row = {"id": f"{group}-{number}", "group": group, "prompt": scrub(render_prompt(question)), "text": text}
741
+ (val if number == len(questions) - 1 else train).append(row)
742
+ return train, val