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/relink.py
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
"""Obsidian graph links behind `keepfold relink`, and the helpers new writes use.
|
|
2
|
+
|
|
3
|
+
Obsidian draws `[[links]]` from note bodies and `"[[x]]"` strings in properties, resolving them
|
|
4
|
+
by path or file name, case-insensitively. Keepfold adds what its graph has but Obsidian's lacks:
|
|
5
|
+
an `Up: [[...]]` line (session -> journal day -> month page -> topic map, people page -> hub),
|
|
6
|
+
the generated people hub `notes/people.md` (public pages only, as index.md lists them), plain
|
|
7
|
+
frontmatter edges as `"[[id]]"` (the form `keepfold_add` already writes), and a report of
|
|
8
|
+
unresolved links: near matches are rewritten, junk (code like `df[['a']]`) is escaped to
|
|
9
|
+
`\\[\\[...]]`, and slug-like targets are listed as missing notes. Every write goes through
|
|
10
|
+
`keepfold.vault`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from ruamel.yaml import YAMLError
|
|
21
|
+
|
|
22
|
+
from keepfold.catalog import page_slug
|
|
23
|
+
from keepfold.index import EDGE_KEYS, _edge_targets, _target
|
|
24
|
+
from keepfold.vault import (
|
|
25
|
+
HEADING_RE,
|
|
26
|
+
ID_RE,
|
|
27
|
+
PRIVATE_BROWSE_DIR,
|
|
28
|
+
Note,
|
|
29
|
+
Vault,
|
|
30
|
+
VaultError,
|
|
31
|
+
_dump_fm,
|
|
32
|
+
_load_fm,
|
|
33
|
+
_newline,
|
|
34
|
+
_section,
|
|
35
|
+
_split,
|
|
36
|
+
_to_yaml,
|
|
37
|
+
is_private,
|
|
38
|
+
truthy,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
TOPIC_MAP = "my-topic-map" # the imported topic hub (notes/); month pages link it if it exists
|
|
42
|
+
HUB = "people" # notes/people.md
|
|
43
|
+
DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
|
|
44
|
+
LINK_RE = re.compile(r"\[\[([^\]\n]*)\]\]")
|
|
45
|
+
# a fenced block or inline code span (Obsidian draws no links there), else a [[link]]
|
|
46
|
+
TOKEN_RE = re.compile(r"(?P<code>^(?P<f>```|~~~).*?^(?P=f)[^\n]*$|`[^`\n]*`)"
|
|
47
|
+
r"|\[\[(?P<t>[^\]\n]*)\]\]", re.M | re.S)
|
|
48
|
+
EDGES = tuple(k for k in EDGE_KEYS if k != "tests") # tests maps concept:x to weights
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _tgt(raw: str) -> str:
|
|
52
|
+
"""The link target: `[[x|alias]]`, `[[x#h]]` and `[[x^b]]` -> x."""
|
|
53
|
+
return re.split(r"[|#^]", raw, maxsplit=1)[0].strip()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _parts(text: str) -> tuple[str, str]:
|
|
57
|
+
"""(frontmatter with fences, body); ('', text) without frontmatter or when it is broken."""
|
|
58
|
+
try:
|
|
59
|
+
p = _split(text)
|
|
60
|
+
except ValueError:
|
|
61
|
+
return "", text
|
|
62
|
+
return ("".join(p[:3]), p[3]) if p else ("", text)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def links(text: str) -> list[str]:
|
|
66
|
+
"""Raw link texts Obsidian sees: frontmatter, and the body outside code."""
|
|
67
|
+
head, body = _parts(text)
|
|
68
|
+
return LINK_RE.findall(head) + [m["t"] for m in TOKEN_RE.finditer(body) if m["t"] is not None]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def has_link(text: str, target: str) -> bool:
|
|
72
|
+
t = target.lower()
|
|
73
|
+
return any((x := _tgt(r).lower().removesuffix(".md")) == t or x.endswith("/" + t)
|
|
74
|
+
for r in links(text))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def with_up(text: str, target: str, label: str = "Up") -> str:
|
|
78
|
+
"""`text` with a `label: [[target]]` line under its H1 (or atop the body), unless it
|
|
79
|
+
already links `target`."""
|
|
80
|
+
if has_link(text, target):
|
|
81
|
+
return text
|
|
82
|
+
head, body = _parts(text)
|
|
83
|
+
nl = _newline(text) if text else "\n"
|
|
84
|
+
lines = body.splitlines(keepends=True)
|
|
85
|
+
at = 1 if lines and lines[0].startswith("# ") else 0
|
|
86
|
+
if at and not lines[0].endswith("\n"):
|
|
87
|
+
lines[0] += nl
|
|
88
|
+
new = [nl] if at else []
|
|
89
|
+
new.append(f"{label}: [[{target}]]{nl}")
|
|
90
|
+
if at < len(lines) and lines[at].strip():
|
|
91
|
+
new.append(nl)
|
|
92
|
+
lines[at:at] = new
|
|
93
|
+
return head + "".join(lines)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def journal_up(vault: Vault, day: str) -> str | None:
|
|
97
|
+
"""What journal page `day` links up to: its month page `YYYY-MM-01`, or for a month page
|
|
98
|
+
the topic map; None when that page does not exist."""
|
|
99
|
+
month = day[:8] + "01"
|
|
100
|
+
if day != month:
|
|
101
|
+
return month if vault.path_for("journal", month).is_file() else None
|
|
102
|
+
return TOPIC_MAP if vault.path_for("note", TOPIC_MAP).is_file() else None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def hub_text(vault: Vault) -> str:
|
|
106
|
+
"""The people hub: a link per public people page; private pages are left out, as in
|
|
107
|
+
index.md, so the hub never shows they exist."""
|
|
108
|
+
from keepfold.people import PREFIX # lazy: people imports this module
|
|
109
|
+
|
|
110
|
+
rows = [f"- [[{PREFIX}{n.id}]]" for n in vault.iter_notes("person") if not is_private(n)]
|
|
111
|
+
return (f'---\nid: "{HUB}"\ntitle: "People"\nkind: "note"\nnote_type: "structure"\n'
|
|
112
|
+
"tags: []\nrelated: []\n---\n# People\n\n"
|
|
113
|
+
"Generated by Keepfold from people/ (`keepfold relink`); private pages are left out.\n"
|
|
114
|
+
"\n## Pages\n" + ("\n".join(rows) or "- none") + "\n")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def with_row(text: str, heading: str, target: str, before=()) -> str:
|
|
118
|
+
"""`text` with `- [[target]]` at the end of its `## heading` section (made before the first
|
|
119
|
+
`before` heading present, else at the end), unless it already links `target`."""
|
|
120
|
+
if has_link(text, target):
|
|
121
|
+
return text
|
|
122
|
+
head, body = _parts(text)
|
|
123
|
+
nl = _newline(text) if text else "\n"
|
|
124
|
+
lines = body.splitlines(keepends=True)
|
|
125
|
+
if lines and not lines[-1].endswith("\n"):
|
|
126
|
+
lines[-1] += nl
|
|
127
|
+
row = f"- [[{target}]]{nl}"
|
|
128
|
+
try:
|
|
129
|
+
_, e = _section(lines, heading)
|
|
130
|
+
while not lines[e - 1].strip():
|
|
131
|
+
e -= 1
|
|
132
|
+
lines[e:e] = [row]
|
|
133
|
+
except VaultError:
|
|
134
|
+
at = next((i for i, ln in enumerate(lines) if (m := HEADING_RE.match(ln.rstrip("\r\n")))
|
|
135
|
+
and len(m.group(1)) == 2 and m.group(2) in before), len(lines))
|
|
136
|
+
new = [f"## {heading}{nl}", row]
|
|
137
|
+
if at < len(lines):
|
|
138
|
+
new.append(nl)
|
|
139
|
+
if at and lines[at - 1].strip():
|
|
140
|
+
new.insert(0, nl)
|
|
141
|
+
lines[at:at] = new
|
|
142
|
+
return head + "".join(lines)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _norm(s: str) -> str:
|
|
146
|
+
return re.sub(r"[\s_-]+", " ", str(s).lower().replace("&", " and ")).strip()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def domain_hubs(fields: dict[str, dict]) -> list[tuple[str, str]]:
|
|
150
|
+
"""(domain id, hub id) pairs from public pages' frontmatter (`fields` maps
|
|
151
|
+
'domain:<id>' / 'hub:<id>' to it). A pair needs a normalised name of the domain (id, title,
|
|
152
|
+
alias) to equal a whole hub name: its title, an alias, or a trailing run of its id's
|
|
153
|
+
segments after `topic-` of at least two segments or one of 5+ characters
|
|
154
|
+
(`system-design` = `topic-software-system-design`; never `os` for `topic-x-cosmos`, nor
|
|
155
|
+
`data` for `topic-x-data`).
|
|
156
|
+
Of a matched hub and its matched sub-hubs only the most general is kept, shortest id
|
|
157
|
+
first, at most three per domain."""
|
|
158
|
+
def names(f: dict, id: str) -> set[str]:
|
|
159
|
+
al = f.get("aliases")
|
|
160
|
+
al = al if isinstance(al, list) else [al] if isinstance(al, str) else []
|
|
161
|
+
return {n for x in (id, f.get("title") or "", *al) if (n := _norm(x))}
|
|
162
|
+
|
|
163
|
+
hubs = {k[4:]: f for k, f in fields.items() if k.startswith("hub:")}
|
|
164
|
+
hub_names = {}
|
|
165
|
+
for h, f in hubs.items():
|
|
166
|
+
segs = h.removeprefix("topic-").split("-")
|
|
167
|
+
# a lone short segment (data, apis, ml, os) is too ambiguous to name a hub
|
|
168
|
+
hub_names[h] = names(f, "") | {_norm("-".join(segs[i:])) for i in range(len(segs))
|
|
169
|
+
if i < len(segs) - 1 or len(segs[i]) >= 5}
|
|
170
|
+
parent = {h: next((t for t in _edge_targets(f.get("related") or []) if t in hubs and t != h),
|
|
171
|
+
None) for h, f in hubs.items()}
|
|
172
|
+
|
|
173
|
+
def line(h: str) -> set[str]: # h and its ancestors
|
|
174
|
+
out = set()
|
|
175
|
+
while h is not None and h not in out:
|
|
176
|
+
out.add(h)
|
|
177
|
+
h = parent[h]
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
pairs = []
|
|
181
|
+
for k, f in sorted(fields.items()):
|
|
182
|
+
if not k.startswith("domain:"):
|
|
183
|
+
continue
|
|
184
|
+
d = k[7:]
|
|
185
|
+
mine = names(f, d)
|
|
186
|
+
kept: list[str] = []
|
|
187
|
+
for h in sorted((h for h in hubs if hub_names[h] & mine), key=lambda h: (len(h), h)):
|
|
188
|
+
if len(kept) < 3 and not any(x in line(h) or h in line(x) for x in kept):
|
|
189
|
+
kept.append(h)
|
|
190
|
+
pairs += [(d, h) for h in kept]
|
|
191
|
+
return pairs
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
Fixes = dict[Path, list[tuple[str, Callable[[str], str]]]]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def people_fixes(vault: Vault) -> Fixes:
|
|
198
|
+
"""Hub, `People: [[people]]` on me/profile and `Up: [[people]]` on each people page;
|
|
199
|
+
nothing until the first people page (a forgotten last page still empties the hub)."""
|
|
200
|
+
pages = [p for p in sorted((vault.root / "people").glob("*.md")) if ID_RE.fullmatch(p.stem)]
|
|
201
|
+
path = vault.path_for("note", HUB)
|
|
202
|
+
if not pages and not path.is_file():
|
|
203
|
+
return {}
|
|
204
|
+
hub = hub_text(vault)
|
|
205
|
+
out: Fixes = {path: [("people_hub", lambda _t: hub)]}
|
|
206
|
+
for p in pages:
|
|
207
|
+
out[p] = [("people_up", lambda t: with_up(t, HUB))]
|
|
208
|
+
profile = vault.path_for("me", "profile")
|
|
209
|
+
if profile.is_file():
|
|
210
|
+
out[profile] = [("profile_hub", lambda t: with_up(t, HUB, "People"))]
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def apply(vault: Vault, fixes: Fixes) -> Counter:
|
|
215
|
+
"""Write each fixed file through the vault (rereading under the lock); count changed files
|
|
216
|
+
per fix kind."""
|
|
217
|
+
done = Counter()
|
|
218
|
+
with vault.lock():
|
|
219
|
+
for path, fns in fixes.items():
|
|
220
|
+
def change(text: str, fns=fns) -> str:
|
|
221
|
+
for kind, fn in fns:
|
|
222
|
+
new = fn(text)
|
|
223
|
+
if new != text:
|
|
224
|
+
done[kind] += 1
|
|
225
|
+
text = new
|
|
226
|
+
return text
|
|
227
|
+
|
|
228
|
+
if path.is_file():
|
|
229
|
+
vault._mutate(path, change)
|
|
230
|
+
elif new := change(""):
|
|
231
|
+
vault.write_text(path, new)
|
|
232
|
+
return done
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ---- the whole-vault pass (`keepfold relink`) -----------------------------------------------
|
|
236
|
+
|
|
237
|
+
_KIND_OF = {d: k for k, d in Vault.KIND_DIRS.items()}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _hidden(root: Path, p: Path, text: str) -> bool:
|
|
241
|
+
"""A page whose links and path the report never names: browse/private/ and any page
|
|
242
|
+
`is_private` calls private (people pages unless `private: false`)."""
|
|
243
|
+
parts = p.relative_to(root).parts
|
|
244
|
+
if parts[:2] == tuple(PRIVATE_BROWSE_DIR.split("/")):
|
|
245
|
+
return True
|
|
246
|
+
try:
|
|
247
|
+
sp = _split(text)
|
|
248
|
+
f = _load_fm(sp[1]) if sp else {}
|
|
249
|
+
except Exception: # YAML errors are not ValueErrors; broken frontmatter may say private
|
|
250
|
+
return True
|
|
251
|
+
kind = _KIND_OF.get(parts[0]) if len(parts) == 2 else None
|
|
252
|
+
return is_private(Note(p, kind, p.stem, f, ""))
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _pages(root: Path) -> list[Path]:
|
|
256
|
+
return [p for p in root.rglob("*") if p.is_file()
|
|
257
|
+
and not any(s.startswith(".") for s in p.relative_to(root).parts[:-1])]
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class _Names:
|
|
261
|
+
"""Obsidian-style resolution over the vault's files (any extension)."""
|
|
262
|
+
|
|
263
|
+
def __init__(self, root: Path, files: list[Path]):
|
|
264
|
+
self.by_path: dict[str, str] = {}
|
|
265
|
+
self.by_name: dict[str, str] = {}
|
|
266
|
+
for p in sorted(files, key=lambda p: (len(p.relative_to(root).parts), str(p))):
|
|
267
|
+
rel = p.relative_to(root).as_posix()
|
|
268
|
+
keys = [rel.lower()]
|
|
269
|
+
if p.suffix == ".md":
|
|
270
|
+
keys.append(rel[:-3].lower())
|
|
271
|
+
for k in keys:
|
|
272
|
+
self.by_path.setdefault(k, rel)
|
|
273
|
+
self.by_name.setdefault(k.rsplit("/", 1)[-1], rel)
|
|
274
|
+
|
|
275
|
+
def resolve(self, target: str) -> str | None:
|
|
276
|
+
t = target.replace("\\", "/").lower()
|
|
277
|
+
if hit := self.by_path.get(t) or self.by_path.get(t + ".md"):
|
|
278
|
+
return hit
|
|
279
|
+
if "/" not in t:
|
|
280
|
+
return self.by_name.get(t)
|
|
281
|
+
return next((v for k, v in self.by_path.items() if k.endswith("/" + t)), None)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def classify(target: str, ids: set[str]) -> tuple[str, str | None]:
|
|
285
|
+
"""('near', id) for a note id the target misspells (case, slug, folder prefix);
|
|
286
|
+
('missing', None) for a slug-like id that should be a note; ('junk', None) otherwise."""
|
|
287
|
+
base = target.replace("\\", "/").rsplit("/", 1)[-1].removesuffix(".md").strip().lower()
|
|
288
|
+
for key in (base, re.sub(r"[^a-z0-9.]+", "-", base).strip("-"), page_slug(base)):
|
|
289
|
+
if key in ids:
|
|
290
|
+
return "near", key
|
|
291
|
+
if ID_RE.fullmatch(base) and "-" in base and not base.replace("-", "").isdigit():
|
|
292
|
+
return "missing", None
|
|
293
|
+
return "junk", None
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _rewrite(text: str, act: dict[str, tuple[str, str | None]], fixed: Counter) -> str:
|
|
297
|
+
"""Near-match links get the right id (frontmatter and body); junk is escaped (body only:
|
|
298
|
+
a backslash is no valid escape inside a YAML string)."""
|
|
299
|
+
head, body = _parts(text)
|
|
300
|
+
|
|
301
|
+
def near(raw: str) -> str | None:
|
|
302
|
+
a = act.get(_tgt(raw))
|
|
303
|
+
return a[1] + raw[len(raw.split("|")[0].split("#")[0].split("^")[0]):] \
|
|
304
|
+
if a and a[0] == "near" else None
|
|
305
|
+
|
|
306
|
+
def fm(m: re.Match) -> str:
|
|
307
|
+
new = near(m[1])
|
|
308
|
+
if new is None:
|
|
309
|
+
return m[0]
|
|
310
|
+
fixed[_tgt(m[1])] += 1
|
|
311
|
+
return f"[[{new}]]"
|
|
312
|
+
|
|
313
|
+
def bd(m: re.Match) -> str:
|
|
314
|
+
if m["t"] is None or not (a := act.get(_tgt(m["t"]))) or a[0] == "missing":
|
|
315
|
+
return m[0]
|
|
316
|
+
fixed[_tgt(m["t"])] += 1
|
|
317
|
+
return f"[[{near(m['t'])}]]" if a[0] == "near" else f"\\[\\[{m['t']}]]"
|
|
318
|
+
|
|
319
|
+
return LINK_RE.sub(fm, head) + TOKEN_RE.sub(bd, body)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _fm_links(text: str, exists: Callable[[str], bool]) -> str:
|
|
323
|
+
"""Plain frontmatter edge ids (`related: [x]`) as `"[[x]]"` when note x exists."""
|
|
324
|
+
try:
|
|
325
|
+
parts = _split(text)
|
|
326
|
+
if parts is None:
|
|
327
|
+
return text
|
|
328
|
+
head, fm, close, body = parts
|
|
329
|
+
data = _load_fm(fm)
|
|
330
|
+
except (ValueError, YAMLError): # broken YAML: leave the page as it is
|
|
331
|
+
return text
|
|
332
|
+
changed = False
|
|
333
|
+
for key in EDGES:
|
|
334
|
+
v = data.get(key)
|
|
335
|
+
items = list(v) if isinstance(v, list) else [v] if isinstance(v, str) else []
|
|
336
|
+
new = [f"[[{t}]]" if isinstance(x, str) and not x.strip().startswith("[[")
|
|
337
|
+
and (t := _target(x)) and exists(t) else x for x in items]
|
|
338
|
+
if new != items:
|
|
339
|
+
data[key] = _to_yaml(new if isinstance(v, list) else new[0])
|
|
340
|
+
changed = True
|
|
341
|
+
return head + _dump_fm(data, _newline(text)) + close + body if changed else text
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def orphans(texts: dict[str, str], names: _Names) -> Counter:
|
|
345
|
+
"""Pages with no resolved [[link]] in or out, counted by top folder ('(root)' at the top)."""
|
|
346
|
+
out, inbound = {}, Counter()
|
|
347
|
+
for rel, text in texts.items():
|
|
348
|
+
dst = {d for r in links(text) if (t := _tgt(r)) and (d := names.resolve(t))
|
|
349
|
+
and d.endswith(".md") and d != rel}
|
|
350
|
+
out[rel] = dst
|
|
351
|
+
inbound.update(dst)
|
|
352
|
+
return Counter(rel.split("/")[0] if "/" in rel else "(root)" for rel in texts
|
|
353
|
+
if not out[rel] and not inbound[rel])
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def run(vault: Vault, dry_run: bool = True) -> dict:
|
|
357
|
+
"""Plan (and unless `dry_run`, write) every fix; returns orphans before and after, files
|
|
358
|
+
changed per fix kind, the unresolved-link rows and the frontmatter edges converted."""
|
|
359
|
+
root = vault.root
|
|
360
|
+
files = _pages(root)
|
|
361
|
+
md = [p for p in files if p.suffix == ".md"]
|
|
362
|
+
texts = {p.relative_to(root).as_posix(): p.read_bytes().decode("utf-8", "replace")
|
|
363
|
+
for p in md}
|
|
364
|
+
names = _Names(root, files)
|
|
365
|
+
kind_dirs = {d for k in vault.KIND_DIRS for d in vault.dirs(k)}
|
|
366
|
+
notes = [p for p in md if p.parent.relative_to(root).as_posix() in kind_dirs
|
|
367
|
+
and ID_RE.fullmatch(p.stem)]
|
|
368
|
+
note_ids = {p.stem for p in notes} # ids are unique across kinds (Vault.create_note)
|
|
369
|
+
|
|
370
|
+
# unresolved links, by target; every page's links are fixed, but only public pages are
|
|
371
|
+
# reported, so a private page's targets and path never reach the output
|
|
372
|
+
seen: dict[str, dict] = {}
|
|
373
|
+
targets: set[str] = set()
|
|
374
|
+
for p in md:
|
|
375
|
+
rel = p.relative_to(root).as_posix()
|
|
376
|
+
text = texts[rel]
|
|
377
|
+
hide = None
|
|
378
|
+
for r in links(text):
|
|
379
|
+
t = _tgt(r)
|
|
380
|
+
if t and not names.resolve(t):
|
|
381
|
+
targets.add(t)
|
|
382
|
+
if hide is None:
|
|
383
|
+
hide = _hidden(root, p, text)
|
|
384
|
+
if not hide:
|
|
385
|
+
row = seen.setdefault(t, {"target": t, "count": 0, "example": rel})
|
|
386
|
+
row["count"] += 1
|
|
387
|
+
act = {t: classify(t, note_ids) for t in targets}
|
|
388
|
+
|
|
389
|
+
fixes: Fixes = {}
|
|
390
|
+
fixed = Counter()
|
|
391
|
+
|
|
392
|
+
def add(p: Path, kind: str, fn) -> None:
|
|
393
|
+
fixes.setdefault(p, []).append((kind, fn))
|
|
394
|
+
|
|
395
|
+
for p in notes:
|
|
396
|
+
kind_dir, day = p.parent.name, p.stem
|
|
397
|
+
if kind_dir == "sessions" and DAY_RE.match(day) and \
|
|
398
|
+
vault.path_for("journal", day[:10]).is_file():
|
|
399
|
+
add(p, "session_up", lambda t, d=day[:10]: with_up(t, d))
|
|
400
|
+
if kind_dir == "journal" and DAY_RE.fullmatch(day) and (up := journal_up(vault, day)):
|
|
401
|
+
add(p, "journal_up", lambda t, u=up: with_up(t, u))
|
|
402
|
+
if act:
|
|
403
|
+
add(p, "links_fixed", lambda t: _rewrite(t, act, fixed))
|
|
404
|
+
add(p, "frontmatter_links", lambda t: _fm_links(t, note_ids.__contains__))
|
|
405
|
+
for p, fns in people_fixes(vault).items():
|
|
406
|
+
fixes.setdefault(p, []).extend(fns)
|
|
407
|
+
from keepfold.topics import CONV, WATCHED # lazy: topics imports this module
|
|
408
|
+
|
|
409
|
+
fields = {}
|
|
410
|
+
for p in notes:
|
|
411
|
+
if p.parent.name not in ("domains", "notes") or p.stem == TOPIC_MAP:
|
|
412
|
+
continue
|
|
413
|
+
try:
|
|
414
|
+
sp = _split(texts[p.relative_to(root).as_posix()])
|
|
415
|
+
f = _load_fm(sp[1]) if sp else None
|
|
416
|
+
except (ValueError, YAMLError):
|
|
417
|
+
continue
|
|
418
|
+
if f is None or truthy(f.get("private")):
|
|
419
|
+
continue
|
|
420
|
+
if p.parent.name == "domains":
|
|
421
|
+
fields[f"domain:{p.stem}"] = f
|
|
422
|
+
elif isinstance(f.get("tags"), list) and "topic" in f["tags"]:
|
|
423
|
+
fields[f"hub:{p.stem}"] = f
|
|
424
|
+
pairs = domain_hubs(fields)
|
|
425
|
+
# the hub row sits outside the sections `topics.build` regenerates, so rebuilds keep it
|
|
426
|
+
hub_heads = ("Sub-topics", "Subtopics", "Areas", *CONV, WATCHED)
|
|
427
|
+
for d, h in pairs:
|
|
428
|
+
add(vault.path_for("domain", d), "domain_topics", lambda t, h=h: with_row(t, "Topics", h))
|
|
429
|
+
add(vault.path_for("note", h), "hub_domains",
|
|
430
|
+
lambda t, d=d: with_row(t, "Study domains", d, before=hub_heads))
|
|
431
|
+
|
|
432
|
+
after = dict(texts) # predicted: every fix applied to the text read above
|
|
433
|
+
counts = Counter()
|
|
434
|
+
for p, fns in fixes.items():
|
|
435
|
+
rel = p.relative_to(root).as_posix()
|
|
436
|
+
text = texts.get(rel, "")
|
|
437
|
+
for kind, fn in fns:
|
|
438
|
+
new = fn(text)
|
|
439
|
+
if new != text:
|
|
440
|
+
counts[kind] += 1
|
|
441
|
+
text = new
|
|
442
|
+
if text:
|
|
443
|
+
after[rel] = text
|
|
444
|
+
if not dry_run:
|
|
445
|
+
fixed.clear()
|
|
446
|
+
counts = apply(vault, fixes) # rereads each file under the lock
|
|
447
|
+
rows = [{**row, "class": act[t][0], "to": act[t][1], "fixed": min(fixed[t], row["count"])}
|
|
448
|
+
for t, row in sorted(seen.items(), key=lambda kv: (-kv[1]["count"], kv[0]))]
|
|
449
|
+
hub = vault.path_for("note", HUB)
|
|
450
|
+
new_files = files + [hub] if hub.relative_to(root).as_posix() in after else files
|
|
451
|
+
return {"orphans_before": orphans(texts, names),
|
|
452
|
+
"orphans_after": orphans(after, _Names(root, new_files)),
|
|
453
|
+
"changed": counts, "unresolved": rows, "domain_hubs": pairs}
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def report_lines(out: dict) -> list[str]:
|
|
457
|
+
b, a = out["orphans_before"], out["orphans_after"]
|
|
458
|
+
lines = [f"orphans: {sum(b.values())} before, {sum(a.values())} after"]
|
|
459
|
+
lines += [f" {k}: {b[k]} -> {a[k]}" for k in sorted(b | a, key=lambda k: -b[k])]
|
|
460
|
+
lines.append("files changed: " + (", ".join(f"{k} {n}" for k, n in
|
|
461
|
+
sorted(out["changed"].items())) or "none"))
|
|
462
|
+
pairs = out.get("domain_hubs", [])
|
|
463
|
+
lines.append(f"study domains joined to topic hubs: {len(pairs)} pairs")
|
|
464
|
+
lines += [f" [[{d}]] <-> [[{h}]]" for d, h in pairs]
|
|
465
|
+
rows = out["unresolved"]
|
|
466
|
+
by = Counter()
|
|
467
|
+
for r in rows:
|
|
468
|
+
by[r["class"]] += r["count"]
|
|
469
|
+
lines.append(f"unresolved links: {sum(by.values())} in {len(rows)} targets ("
|
|
470
|
+
+ ", ".join(f"{k} {by[k]}" for k in ("near", "missing", "junk")) + ")")
|
|
471
|
+
for r in rows:
|
|
472
|
+
to = f" -> [[{r['to']}]]" if r["to"] else ""
|
|
473
|
+
left = r["count"] - r["fixed"]
|
|
474
|
+
lines.append(f" {r['class']:<7} {r['count']:>3} [[{r['target']}]]{to} "
|
|
475
|
+
f"e.g. {r['example']}" + (f" ({left} left)" if left and
|
|
476
|
+
r["class"] != "missing" else ""))
|
|
477
|
+
return lines
|