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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/catalog.py
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
"""Concept catalog: domain -> area -> concept, name resolution and dedup (SPEC §0 U2/U3, §4).
|
|
2
|
+
|
|
3
|
+
`catalog.yaml` is the machine-readable mirror of domains/, areas/ and concepts/. Every write
|
|
4
|
+
goes through `keepfold.vault` (lock + atomic replace).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import difflib
|
|
12
|
+
import hashlib
|
|
13
|
+
import io
|
|
14
|
+
import re
|
|
15
|
+
import unicodedata
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from ruamel.yaml import YAML
|
|
20
|
+
from ruamel.yaml.comments import CommentedMap, CommentedSeq
|
|
21
|
+
|
|
22
|
+
from keepfold.events import local_day
|
|
23
|
+
from keepfold.index import _edge_targets
|
|
24
|
+
from keepfold.vault import ID_RE, Vault, VaultError, _to_yaml, is_private, parse_error
|
|
25
|
+
from keepfold.vault import _yaml as _vault_yaml
|
|
26
|
+
|
|
27
|
+
CATALOG = "catalog.yaml"
|
|
28
|
+
INBOX = "inbox.md"
|
|
29
|
+
DUP_RATIO = 0.85
|
|
30
|
+
CHILD_KEY = {"domain": "areas", "area": "concepts"}
|
|
31
|
+
PARENT_KIND = {"area": "domain", "concept": "area"}
|
|
32
|
+
KINDS = ("domain", "area", "concept")
|
|
33
|
+
SYNC_KEYS = ("adopted", "updated", "materialised", "skipped")
|
|
34
|
+
SYNC_STAMP = ".keepfold/catalog-sync"
|
|
35
|
+
# path -> ((mtime_ns, size), data): in-process only. Readers share the data; every writer
|
|
36
|
+
# starts from a deep copy (_reload), so the cached tree is never mutated.
|
|
37
|
+
_LOADED: dict[Path, tuple[tuple[int, int], CommentedMap]] = {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Entry:
|
|
42
|
+
id: str
|
|
43
|
+
kind: str # 'domain' | 'area' | 'concept'
|
|
44
|
+
title: str
|
|
45
|
+
aliases: list = field(default_factory=list)
|
|
46
|
+
parent: str | None = None
|
|
47
|
+
domain: str = ""
|
|
48
|
+
requires: list = field(default_factory=list)
|
|
49
|
+
areas: list = field(default_factory=list) # concept only: extra areas beyond `parent`
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def slugify(title: str) -> str:
|
|
53
|
+
"""Title to an id-safe slug (no dots: dots separate domain and area). '' if nothing is left."""
|
|
54
|
+
s = str(title).replace("+", " plus ").replace("#", " sharp ").replace("&", " and ")
|
|
55
|
+
s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()
|
|
56
|
+
s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
|
|
57
|
+
return s[:81].rstrip("-")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def page_slug(title: str) -> str:
|
|
61
|
+
"""slugify for a title that becomes a page id. A title whose slug has no ASCII letter but
|
|
62
|
+
which has a non-ASCII letter or digit ('गणित', '日本語', 'Лекция 3') gets a stable
|
|
63
|
+
t-<8 hex> id instead, so it is not refused and 'Лекция 3' and 'Тема 3' do not both become
|
|
64
|
+
'3'. Every other title keeps its slugify id ('' when it has no letter or digit)."""
|
|
65
|
+
s = slugify(title)
|
|
66
|
+
t = unicodedata.normalize("NFC", " ".join(str(title).split()).casefold())
|
|
67
|
+
if re.search("[a-z]", s) or not any(c.isalnum() and not c.isascii() for c in t):
|
|
68
|
+
return s
|
|
69
|
+
return f"t-{hashlib.blake2s(t.encode(), digest_size=4).hexdigest()}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _yaml() -> YAML:
|
|
73
|
+
y = _vault_yaml()
|
|
74
|
+
y.indent(mapping=2, sequence=4, offset=2) # the vault's catalog layout; round-trips exactly
|
|
75
|
+
return y
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _strs(value) -> list[str]:
|
|
79
|
+
return [str(v) for v in value or []]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Catalog:
|
|
83
|
+
def __init__(self, vault: Vault, data: CommentedMap | None = None):
|
|
84
|
+
self.vault = vault
|
|
85
|
+
self._data = data if data is not None else CommentedMap([("schema", 1),
|
|
86
|
+
("domains", CommentedSeq())])
|
|
87
|
+
self.entries: dict[str, Entry] = {}
|
|
88
|
+
self.adopted = False # set by add()
|
|
89
|
+
self._index()
|
|
90
|
+
|
|
91
|
+
# ---- loading --------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def path(self):
|
|
95
|
+
return self.vault.root / CATALOG
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def load(cls, vault: Vault) -> Catalog:
|
|
99
|
+
path = vault.root / CATALOG
|
|
100
|
+
if not path.is_file():
|
|
101
|
+
return cls(vault)
|
|
102
|
+
st = path.stat()
|
|
103
|
+
key = (st.st_mtime_ns, st.st_size)
|
|
104
|
+
hit = _LOADED.get(path)
|
|
105
|
+
if hit is None or hit[0] != key:
|
|
106
|
+
try:
|
|
107
|
+
data = _yaml().load(path.read_bytes().decode("utf-8"))
|
|
108
|
+
except Exception as e:
|
|
109
|
+
raise VaultError("invalid_argument",
|
|
110
|
+
f"{CATALOG} cannot be parsed: {parse_error(e, 0)}") from e
|
|
111
|
+
if data is None:
|
|
112
|
+
return cls(vault)
|
|
113
|
+
if not isinstance(data, CommentedMap):
|
|
114
|
+
raise VaultError("invalid_argument", f"{CATALOG} is not a mapping.")
|
|
115
|
+
data.setdefault("domains", CommentedSeq())
|
|
116
|
+
hit = _LOADED[path] = (key, data)
|
|
117
|
+
return cls(vault, hit[1])
|
|
118
|
+
|
|
119
|
+
def _index(self) -> None:
|
|
120
|
+
self.entries = {}
|
|
121
|
+
for d in self._data.get("domains") or []:
|
|
122
|
+
self._put(d, "domain", None, str(d["id"]))
|
|
123
|
+
for a in d.get("areas") or []:
|
|
124
|
+
self._put(a, "area", str(d["id"]), str(d["id"]))
|
|
125
|
+
for c in a.get("concepts") or []:
|
|
126
|
+
self._put(c, "concept", str(a["id"]), str(d["id"]))
|
|
127
|
+
|
|
128
|
+
def _put(self, node, kind, parent, domain) -> None:
|
|
129
|
+
id = str(node["id"])
|
|
130
|
+
# a domain's `areas` is its child list; only a concept's `areas` holds extra parents
|
|
131
|
+
self.entries[id] = Entry(id, kind, str(node.get("title") or id), _strs(node.get("aliases")),
|
|
132
|
+
parent, domain, _strs(node.get("requires")),
|
|
133
|
+
_strs(node.get("areas")) if kind == "concept" else [])
|
|
134
|
+
|
|
135
|
+
def _reload(self) -> None:
|
|
136
|
+
"""Fresh, private data from disk; every writer calls this before it edits."""
|
|
137
|
+
self._data = copy.deepcopy(Catalog.load(self.vault)._data)
|
|
138
|
+
self._index()
|
|
139
|
+
|
|
140
|
+
def _save(self) -> None:
|
|
141
|
+
buf = io.StringIO()
|
|
142
|
+
_yaml().dump(self._data, buf)
|
|
143
|
+
self.vault.write_text(self.path, buf.getvalue())
|
|
144
|
+
self._index()
|
|
145
|
+
|
|
146
|
+
def _node(self, id: str) -> tuple[CommentedSeq, CommentedMap]:
|
|
147
|
+
"""The (containing list, mapping) of `id` in the raw catalog data."""
|
|
148
|
+
for d in self._data["domains"]:
|
|
149
|
+
if str(d["id"]) == id:
|
|
150
|
+
return self._data["domains"], d
|
|
151
|
+
for a in d.get("areas") or []:
|
|
152
|
+
if str(a["id"]) == id:
|
|
153
|
+
return d["areas"], a
|
|
154
|
+
for c in a.get("concepts") or []:
|
|
155
|
+
if str(c["id"]) == id:
|
|
156
|
+
return a["concepts"], c
|
|
157
|
+
raise VaultError("unknown_id", f"'{id}' is not in {CATALOG}.")
|
|
158
|
+
|
|
159
|
+
# ---- queries --------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
def _names(self, kinds, skip=()) -> list[tuple[str, str]]:
|
|
162
|
+
"""(casefolded name, id) for every id, title and alias of the given kinds, but none of
|
|
163
|
+
the ids in `skip`."""
|
|
164
|
+
out = []
|
|
165
|
+
for e in self.entries.values():
|
|
166
|
+
if e.kind in kinds and e.id not in skip:
|
|
167
|
+
out += [(n.casefold(), e.id) for n in (e.id, e.title, *e.aliases)]
|
|
168
|
+
return out
|
|
169
|
+
|
|
170
|
+
def resolve(self, name: str, kinds=("concept",), skip=()) -> str:
|
|
171
|
+
"""The id `name` names. `skip`: ids treated as absent (an access-gated caller's hidden
|
|
172
|
+
ids), so a hidden id fails exactly like an unknown one and is never suggested."""
|
|
173
|
+
name = str(name).strip()
|
|
174
|
+
e = self.entries.get(name)
|
|
175
|
+
if e and e.kind in kinds and name not in skip:
|
|
176
|
+
return name
|
|
177
|
+
names = self._names(kinds, skip)
|
|
178
|
+
key = name.casefold()
|
|
179
|
+
# shortcut: a name shared by two entries resolves to the first in catalog order.
|
|
180
|
+
for n, id in names:
|
|
181
|
+
if n == key:
|
|
182
|
+
return id
|
|
183
|
+
slug = page_slug(name)
|
|
184
|
+
if slug:
|
|
185
|
+
for n, id in names:
|
|
186
|
+
if page_slug(n) == slug:
|
|
187
|
+
return id
|
|
188
|
+
code = "unknown_concept" if "concept" in kinds else "unknown_id"
|
|
189
|
+
suggestions = self.suggest(name, kinds, skip=skip)
|
|
190
|
+
hint = f"did you mean {', '.join(suggestions)}?" if suggestions else \
|
|
191
|
+
"add it with keepfold_add or check the spelling."
|
|
192
|
+
raise VaultError(code, f"No {'/'.join(kinds)} named '{name}'; {hint}", suggestions)
|
|
193
|
+
|
|
194
|
+
def suggest(self, name: str, kinds=("concept",), n: int = 3, skip=()) -> list[str]:
|
|
195
|
+
names = self._names(kinds, skip)
|
|
196
|
+
out: list[str] = []
|
|
197
|
+
for hit in difflib.get_close_matches(str(name).casefold(), [m for m, _ in names], n=n * 4):
|
|
198
|
+
for m, id in names:
|
|
199
|
+
if m == hit and id not in out:
|
|
200
|
+
out.append(id)
|
|
201
|
+
return out[:n]
|
|
202
|
+
|
|
203
|
+
def area_hint(self) -> str:
|
|
204
|
+
"""Where a new concept can go: up to 8 non-private area ids, the id format, and the
|
|
205
|
+
calls that make a domain and an area. Walks only domain and area notes (privacy)."""
|
|
206
|
+
private = {n.id for k in ("domain", "area") for n in self.vault.iter_notes(k)
|
|
207
|
+
if is_private(n)}
|
|
208
|
+
areas = [e.id for e in self.entries.values()
|
|
209
|
+
if e.kind == "area" and not {e.id, e.parent, e.domain} & private][:8]
|
|
210
|
+
return (f"Existing areas: {', '.join(areas)}. " if areas else "No areas yet. ") + \
|
|
211
|
+
"An area id is <domain>.<area>, e.g. dbms.database-design; a new one takes " \
|
|
212
|
+
'keepfold_add(kind="domain", title="DBMS") and then keepfold_add(kind="area", ' \
|
|
213
|
+
'title="Database design", parent="dbms"); then add the concept with ' \
|
|
214
|
+
"parent=<area id>."
|
|
215
|
+
|
|
216
|
+
def children(self, id: str) -> list[str]:
|
|
217
|
+
return [e.id for e in self.entries.values() if e.parent == id]
|
|
218
|
+
|
|
219
|
+
def _near_duplicates(self, kind: str, names: list[str], parent: str | None) -> list[str]:
|
|
220
|
+
out = []
|
|
221
|
+
for e in self.entries.values():
|
|
222
|
+
# area ids carry their domain, so "Basics" may exist once per domain
|
|
223
|
+
if e.kind != kind or (kind == "area" and e.parent != parent):
|
|
224
|
+
continue
|
|
225
|
+
for mine in names:
|
|
226
|
+
if any(difflib.SequenceMatcher(None, mine.casefold(), o.casefold()).ratio()
|
|
227
|
+
>= DUP_RATIO or page_slug(mine) == page_slug(o)
|
|
228
|
+
for o in (e.title, *e.aliases)):
|
|
229
|
+
out.append(e.id)
|
|
230
|
+
break
|
|
231
|
+
return out
|
|
232
|
+
|
|
233
|
+
# ---- writes ---------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
def add(self, kind: str, title: str, parent: str | None = None, aliases=(), requires=(),
|
|
236
|
+
force: bool = False, areas=()) -> str:
|
|
237
|
+
if kind not in KINDS:
|
|
238
|
+
raise VaultError("invalid_argument", "kind must be domain, area or concept.")
|
|
239
|
+
if areas and kind != "concept":
|
|
240
|
+
raise VaultError("invalid_argument", "Only a concept takes areas.")
|
|
241
|
+
title = str(title).strip()
|
|
242
|
+
aliases = [str(a).strip() for a in aliases if str(a).strip()]
|
|
243
|
+
slug = page_slug(title)
|
|
244
|
+
if not slug:
|
|
245
|
+
raise VaultError("invalid_argument", "The title needs at least one letter or digit.")
|
|
246
|
+
with self.vault.lock():
|
|
247
|
+
self._reload()
|
|
248
|
+
# a concept note made by hand with no catalog entry: adopt it from its frontmatter
|
|
249
|
+
adopt = kind == "concept" and slug not in self.entries and \
|
|
250
|
+
self.vault.path_for(kind, slug).is_file()
|
|
251
|
+
note_reqs, note_areas = [], []
|
|
252
|
+
if adopt:
|
|
253
|
+
f = self.vault.read(kind, slug).fields
|
|
254
|
+
note_areas = _edge_targets(f.get("areas") or [])
|
|
255
|
+
parent = (_edge_targets(f.get("parent")) or [parent])[0]
|
|
256
|
+
title = str(f.get("title") or title)
|
|
257
|
+
mine = f.get("aliases") or []
|
|
258
|
+
mine = _strs(mine if isinstance(mine, list) else [mine])
|
|
259
|
+
aliases = list(dict.fromkeys([*mine, *aliases]))
|
|
260
|
+
note_reqs = _edge_targets(f.get("requires") or [])
|
|
261
|
+
if kind == "domain":
|
|
262
|
+
if parent is not None:
|
|
263
|
+
raise VaultError("invalid_argument", "A domain has no parent.")
|
|
264
|
+
elif not parent:
|
|
265
|
+
raise VaultError("invalid_argument", f"A {kind} needs a parent "
|
|
266
|
+
f"{PARENT_KIND[kind]}." +
|
|
267
|
+
(" " + self.area_hint() if kind == "concept" else ""))
|
|
268
|
+
else:
|
|
269
|
+
parent = self.resolve(parent, kinds=(PARENT_KIND[kind],))
|
|
270
|
+
domain = self.entries[parent].domain if parent else None
|
|
271
|
+
reqs = [self.resolve(r) for r in requires]
|
|
272
|
+
for r in note_reqs: # a hand-written requires may name a concept not added yet
|
|
273
|
+
try:
|
|
274
|
+
reqs.append(self.resolve(r))
|
|
275
|
+
except VaultError as e:
|
|
276
|
+
if e.code != "unknown_concept":
|
|
277
|
+
raise
|
|
278
|
+
reqs = list(dict.fromkeys(reqs))
|
|
279
|
+
areas = [self.resolve(a, ("area",)) for a in areas]
|
|
280
|
+
areas += [a for a in note_areas if a in self.entries
|
|
281
|
+
and self.entries[a].kind == "area"] # a hand-written area may be unknown
|
|
282
|
+
areas = [a for a in dict.fromkeys(areas) if a != parent]
|
|
283
|
+
prefix = f"{parent}." if kind == "area" else ""
|
|
284
|
+
base = (prefix + slug)[:81].rstrip("-.")
|
|
285
|
+
# adopting registers the existing note as is, so near-duplicates are not checked
|
|
286
|
+
dups = [] if adopt else self._near_duplicates(kind, [title, *aliases], parent)
|
|
287
|
+
if base in self.entries and base not in dups:
|
|
288
|
+
dups.append(base)
|
|
289
|
+
if dups and not force:
|
|
290
|
+
raise VaultError("duplicate_suggested", f"'{title}' looks like "
|
|
291
|
+
f"{', '.join(dups)}; use the existing one or pass force=true.",
|
|
292
|
+
dups[:3])
|
|
293
|
+
id, n = base, 2
|
|
294
|
+
while id in self.entries: # force on a taken slug: number it
|
|
295
|
+
id = f"{base[:78].rstrip('-.')}-{n}"
|
|
296
|
+
n += 1
|
|
297
|
+
if not ID_RE.fullmatch(id):
|
|
298
|
+
raise VaultError("invalid_id", f"'{id}' is not a valid id; change the title.")
|
|
299
|
+
|
|
300
|
+
e = Entry(id, kind, title, aliases, parent, domain or "", reqs, areas)
|
|
301
|
+
if not adopt:
|
|
302
|
+
self._materialise(e)
|
|
303
|
+
self._attach(_node_of(e), parent)
|
|
304
|
+
self._save()
|
|
305
|
+
self.adopted = adopt # read by callers to say "adopted" instead of "added"
|
|
306
|
+
return id
|
|
307
|
+
|
|
308
|
+
def _attach(self, node: CommentedMap, parent: str | None) -> None:
|
|
309
|
+
if parent is None:
|
|
310
|
+
self._data["domains"].append(node)
|
|
311
|
+
return
|
|
312
|
+
pnode = self._node(parent)[1]
|
|
313
|
+
key = CHILD_KEY[self.entries[parent].kind]
|
|
314
|
+
if pnode.get(key) is None:
|
|
315
|
+
pnode[key] = CommentedSeq()
|
|
316
|
+
pnode[key].append(node)
|
|
317
|
+
|
|
318
|
+
def _materialise(self, e: Entry) -> None:
|
|
319
|
+
"""Create the note for entry `e` (create_note refuses to overwrite one)."""
|
|
320
|
+
fields: dict = {"title": e.title}
|
|
321
|
+
if e.kind == "domain":
|
|
322
|
+
fields.update(kind="domain", aliases=e.aliases)
|
|
323
|
+
elif e.kind == "area":
|
|
324
|
+
fields.update(kind="area", domain=e.domain, parent=f"[[{e.parent}]]")
|
|
325
|
+
if e.aliases:
|
|
326
|
+
fields["aliases"] = e.aliases
|
|
327
|
+
else:
|
|
328
|
+
fields.update(parent=f"[[{e.parent}]]", domain=e.domain, aliases=e.aliases,
|
|
329
|
+
requires=[f"[[{r}]]" for r in e.requires], mistakes=[])
|
|
330
|
+
if e.areas:
|
|
331
|
+
fields["areas"] = [f"[[{a}]]" for a in e.areas]
|
|
332
|
+
self.vault.create_note(e.kind, e.id, fields, f"# {e.title}\n\n## Notes\n")
|
|
333
|
+
|
|
334
|
+
def _sync(self) -> dict[str, list[str]]:
|
|
335
|
+
"""Make the catalog agree with the domain, area and concept notes; never deletes."""
|
|
336
|
+
self._reload()
|
|
337
|
+
report: dict[str, list[str]] = {k: [] for k in SYNC_KEYS}
|
|
338
|
+
notes = {}
|
|
339
|
+
for kind in KINDS:
|
|
340
|
+
for note in self.vault.iter_notes(kind):
|
|
341
|
+
if "merged_into" not in note.fields: # merge took it out of the catalog
|
|
342
|
+
notes[note.id] = (kind, note.fields)
|
|
343
|
+
changed, adopted = False, {}
|
|
344
|
+
for kind in KINDS: # parents first, so a hand-made area can hold a hand-made concept
|
|
345
|
+
for id, (k, f) in notes.items():
|
|
346
|
+
if k != kind:
|
|
347
|
+
continue
|
|
348
|
+
e = self.entries.get(id)
|
|
349
|
+
if e and e.kind != kind:
|
|
350
|
+
report["skipped"].append(f"{id}: the catalog has it as a {e.kind}")
|
|
351
|
+
continue
|
|
352
|
+
parent = None
|
|
353
|
+
if kind != "domain":
|
|
354
|
+
parent = (_edge_targets(f.get("parent")) or [None])[0]
|
|
355
|
+
if parent is None and e:
|
|
356
|
+
parent = e.parent
|
|
357
|
+
elif parent is None and kind == "area": # areas/<domain>.<slug>.md
|
|
358
|
+
parent = str(f.get("domain") or id.partition(".")[0])
|
|
359
|
+
want = PARENT_KIND[kind]
|
|
360
|
+
if parent not in self.entries or self.entries[parent].kind != want:
|
|
361
|
+
report["skipped"].append(f"{id}: parent {parent or '(none)'} is not "
|
|
362
|
+
f"a known {want}")
|
|
363
|
+
continue
|
|
364
|
+
title = str(f.get("title") or (e.title if e else id))
|
|
365
|
+
areas = []
|
|
366
|
+
if kind == "concept": # frontmatter wins: no `areas` means none
|
|
367
|
+
areas = [a for a in dict.fromkeys(_edge_targets(f.get("areas") or []))
|
|
368
|
+
if a != parent and getattr(self.entries.get(a), "kind", "") == "area"]
|
|
369
|
+
if e is None:
|
|
370
|
+
mine = f.get("aliases") or []
|
|
371
|
+
mine = _strs(mine if isinstance(mine, list) else [mine])
|
|
372
|
+
domain = self.entries[parent].domain if parent else id
|
|
373
|
+
node = _node_of(Entry(id, kind, title, mine, parent, domain, [], areas))
|
|
374
|
+
self._attach(node, parent)
|
|
375
|
+
adopted[id] = (node, f)
|
|
376
|
+
report["adopted"].append(id)
|
|
377
|
+
elif (e.title, e.parent, e.areas) != (title, parent, areas):
|
|
378
|
+
seq, node = self._node(id)
|
|
379
|
+
node["title"] = _to_yaml(title)
|
|
380
|
+
if areas or "areas" in node:
|
|
381
|
+
node["areas"] = _to_yaml(areas)
|
|
382
|
+
if parent != e.parent:
|
|
383
|
+
seq.remove(node)
|
|
384
|
+
self._attach(node, parent)
|
|
385
|
+
report["updated"].append(id)
|
|
386
|
+
else:
|
|
387
|
+
continue
|
|
388
|
+
changed = True
|
|
389
|
+
if changed:
|
|
390
|
+
self._index() # once per kind: the next kind looks up these as parents
|
|
391
|
+
for id, (node, f) in adopted.items(): # requires last: they may name later adoptions
|
|
392
|
+
if "requires" not in node: # only concepts have requires
|
|
393
|
+
continue
|
|
394
|
+
reqs = []
|
|
395
|
+
for r in _edge_targets(f.get("requires") or []):
|
|
396
|
+
try:
|
|
397
|
+
reqs.append(self.resolve(r))
|
|
398
|
+
except VaultError as err:
|
|
399
|
+
if err.code != "unknown_concept":
|
|
400
|
+
raise
|
|
401
|
+
node["requires"] = _to_yaml([r for r in dict.fromkeys(reqs) if r != id])
|
|
402
|
+
for e in list(self.entries.values()):
|
|
403
|
+
try:
|
|
404
|
+
if e.id in notes or self.vault.path_for(e.kind, e.id).is_file():
|
|
405
|
+
continue # a note that does not parse is left for doctor, never replaced
|
|
406
|
+
self._materialise(e)
|
|
407
|
+
except VaultError as err:
|
|
408
|
+
report["skipped"].append(f"{e.id}: {err}")
|
|
409
|
+
continue
|
|
410
|
+
report["materialised"].append(e.id)
|
|
411
|
+
if changed:
|
|
412
|
+
self._save()
|
|
413
|
+
return report
|
|
414
|
+
|
|
415
|
+
def alias(self, id: str, alias: str) -> None:
|
|
416
|
+
alias = str(alias).strip()
|
|
417
|
+
if not alias:
|
|
418
|
+
raise VaultError("invalid_argument", "The alias is empty.")
|
|
419
|
+
with self.vault.lock():
|
|
420
|
+
self._reload()
|
|
421
|
+
id = self.resolve(id, KINDS)
|
|
422
|
+
e = self.entries[id]
|
|
423
|
+
owner = next((i for n, i in self._names(KINDS) if n == alias.casefold()), None)
|
|
424
|
+
if owner == id:
|
|
425
|
+
return
|
|
426
|
+
if owner:
|
|
427
|
+
raise VaultError("invalid_argument", f"'{alias}' already names '{owner}'; "
|
|
428
|
+
"merge them instead.")
|
|
429
|
+
node = self._node(id)[1]
|
|
430
|
+
node["aliases"] = _to_yaml([*e.aliases, alias])
|
|
431
|
+
self._save()
|
|
432
|
+
self._note_aliases(e.kind, id, [*e.aliases, alias])
|
|
433
|
+
|
|
434
|
+
def _note_aliases(self, kind: str, id: str, aliases: list[str]) -> None:
|
|
435
|
+
try:
|
|
436
|
+
note = self.vault.read(kind, id)
|
|
437
|
+
except VaultError:
|
|
438
|
+
return # catalog-only entry: nothing to mirror
|
|
439
|
+
if "aliases" in note.fields:
|
|
440
|
+
self.vault._edit_fields(kind, id, {"aliases": aliases})
|
|
441
|
+
|
|
442
|
+
def merge(self, src: str, dst: str) -> None:
|
|
443
|
+
"""Fold concept `src` into `dst`. The caller appends the remap event."""
|
|
444
|
+
with self.vault.lock():
|
|
445
|
+
self._reload()
|
|
446
|
+
src, dst = self.resolve(src), self.resolve(dst)
|
|
447
|
+
if src == dst:
|
|
448
|
+
raise VaultError("invalid_argument", "Cannot merge a concept into itself.")
|
|
449
|
+
s, d = self.entries[src], self.entries[dst]
|
|
450
|
+
seen = {d.title.casefold(), *(a.casefold() for a in d.aliases)}
|
|
451
|
+
aliases = list(d.aliases)
|
|
452
|
+
for n in (s.title, *s.aliases):
|
|
453
|
+
if n.casefold() not in seen:
|
|
454
|
+
seen.add(n.casefold())
|
|
455
|
+
aliases.append(n)
|
|
456
|
+
self._node(dst)[1]["aliases"] = _to_yaml(aliases)
|
|
457
|
+
seq, node = self._node(src)
|
|
458
|
+
seq.remove(node)
|
|
459
|
+
for e in self.entries.values(): # keep requires pointing at live ids
|
|
460
|
+
if src in e.requires and e.id != src:
|
|
461
|
+
new = []
|
|
462
|
+
for r in (dst if r == src else r for r in e.requires):
|
|
463
|
+
if r != e.id and r not in new:
|
|
464
|
+
new.append(r)
|
|
465
|
+
self._node(e.id)[1]["requires"] = _to_yaml(new)
|
|
466
|
+
self._save()
|
|
467
|
+
self._note_aliases("concept", dst, aliases)
|
|
468
|
+
try:
|
|
469
|
+
self.vault.read("concept", src)
|
|
470
|
+
except VaultError:
|
|
471
|
+
return
|
|
472
|
+
self.vault._edit_fields("concept", src, {"merged_into": f"[[{dst}]]"})
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _node_of(e: Entry) -> CommentedMap:
|
|
476
|
+
"""The catalog.yaml mapping for a new entry."""
|
|
477
|
+
node = CommentedMap([("id", _to_yaml(e.id)), ("title", _to_yaml(e.title))])
|
|
478
|
+
if e.kind == "domain":
|
|
479
|
+
node["aliases"] = _to_yaml(e.aliases)
|
|
480
|
+
node["areas"] = CommentedSeq()
|
|
481
|
+
elif e.kind == "area":
|
|
482
|
+
if e.aliases:
|
|
483
|
+
node["aliases"] = _to_yaml(e.aliases)
|
|
484
|
+
node["concepts"] = CommentedSeq()
|
|
485
|
+
else:
|
|
486
|
+
node["aliases"] = _to_yaml(e.aliases)
|
|
487
|
+
node["requires"] = _to_yaml(e.requires)
|
|
488
|
+
if e.areas:
|
|
489
|
+
node["areas"] = _to_yaml(e.areas)
|
|
490
|
+
return node
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _signature(vault: Vault) -> str:
|
|
494
|
+
"""File count, newest mtime and total size of catalog.yaml and the catalog notes."""
|
|
495
|
+
# shortcut: misses an edit that keeps the size and backdates the mtime; keep a per-file
|
|
496
|
+
# stat map if that ever matters.
|
|
497
|
+
paths = [vault.root / CATALOG]
|
|
498
|
+
paths += [p for k in KINDS for p in (vault.root / vault.KIND_DIRS[k]).glob("*.md")]
|
|
499
|
+
n = top = size = 0
|
|
500
|
+
for p in paths:
|
|
501
|
+
try:
|
|
502
|
+
st = p.stat()
|
|
503
|
+
except OSError:
|
|
504
|
+
continue
|
|
505
|
+
n, top, size = n + 1, max(top, st.st_mtime_ns), size + st.st_size
|
|
506
|
+
return f"{n} {top} {size}"
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def sync(vault: Vault, if_changed: bool = False) -> dict[str, list[str]]:
|
|
510
|
+
"""Make catalog.yaml agree with domains/, areas/ and concepts/ (frontmatter wins).
|
|
511
|
+
|
|
512
|
+
Adopts notes without entries, takes titles, parents and areas edited in Obsidian, and
|
|
513
|
+
materialises a note for an entry that has none. Never deletes. With `if_changed`, returns
|
|
514
|
+
at once when no catalog file or note changed since the last sync (a stat scan only)."""
|
|
515
|
+
stamp = vault.root / SYNC_STAMP
|
|
516
|
+
if if_changed:
|
|
517
|
+
try:
|
|
518
|
+
if stamp.read_bytes().decode() == _signature(vault):
|
|
519
|
+
return {k: [] for k in SYNC_KEYS}
|
|
520
|
+
except OSError:
|
|
521
|
+
pass
|
|
522
|
+
with vault.lock():
|
|
523
|
+
report = Catalog.load(vault)._sync()
|
|
524
|
+
vault.write_text(stamp, _signature(vault))
|
|
525
|
+
return report
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def inbox_add(vault: Vault, name: str, context: str = "") -> str:
|
|
529
|
+
"""Park an unknown concept name in inbox.md; returns its 'inbox:<slug>' object id."""
|
|
530
|
+
name = " ".join(str(name).split())
|
|
531
|
+
slug = page_slug(name)
|
|
532
|
+
if not slug:
|
|
533
|
+
raise VaultError("invalid_argument", "The name needs at least one letter or digit.")
|
|
534
|
+
context = " ".join(str(context).split())
|
|
535
|
+
today = local_day(dt.datetime.now(dt.UTC)) # the 04:00 rollover, like the journal
|
|
536
|
+
line = f"- [ ] {name} ({context}, {today})" if context else f"- [ ] {name} ({today})"
|
|
537
|
+
|
|
538
|
+
def add(text: str) -> str: # B13: reruns on the reread page if the owner edited it
|
|
539
|
+
lines = text.rstrip("\n").split("\n")
|
|
540
|
+
if any(ln.startswith(f"- [ ] {name} (") for ln in lines):
|
|
541
|
+
return text
|
|
542
|
+
# above the first `## ` section: lines appended at the end landed under
|
|
543
|
+
# `## About me (unconfirmed)` and read as claims waiting for the user's yes
|
|
544
|
+
cut = next((i for i, ln in enumerate(lines) if ln.startswith("## ")), len(lines))
|
|
545
|
+
head, tail = lines[:cut], lines[cut:]
|
|
546
|
+
while len(head) > 1 and not head[-1].strip():
|
|
547
|
+
head.pop()
|
|
548
|
+
head += ([] if head[-1].startswith("- [") else [""]) + [line] # blank after prose
|
|
549
|
+
return "\n".join(head + ([""] + tail if tail else [])) + "\n"
|
|
550
|
+
|
|
551
|
+
vault.update_text(vault.root / INBOX, add, "# Inbox\n")
|
|
552
|
+
return f"inbox:{slug}"
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def resolve_or_inbox(vault: Vault, catalog: Catalog, name: str, context: str = "",
|
|
556
|
+
skip=()) -> str:
|
|
557
|
+
"""'concept:<id>' for a known name; otherwise park it in inbox.md and return 'inbox:<slug>'.
|
|
558
|
+
`skip` as in Catalog.resolve: a hidden name is parked like an unknown one."""
|
|
559
|
+
try:
|
|
560
|
+
return f"concept:{catalog.resolve(name, skip=skip)}"
|
|
561
|
+
except VaultError as e:
|
|
562
|
+
if e.code != "unknown_concept":
|
|
563
|
+
raise
|
|
564
|
+
return inbox_add(vault, name, context)
|