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/index.py
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
"""In-memory SQLite index with FTS5, nodes and edges, rebuilt from a stat-scan per process.
|
|
2
|
+
Unchanged files load from `.keepfold/index-snapshot.json` instead of being parsed again.
|
|
3
|
+
|
|
4
|
+
Backs `keepfold_find` and `keepfold_read` (docs/tools.md). Notes with `private: true`, and catalog
|
|
5
|
+
entries under a private domain or area (`planner.hidden`), never enter the index, so neither
|
|
6
|
+
tool can return them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
import functools
|
|
13
|
+
import html
|
|
14
|
+
import itertools
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import re
|
|
18
|
+
import sqlite3
|
|
19
|
+
import unicodedata
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from types import SimpleNamespace
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from keepfold.levels import GLYPH
|
|
26
|
+
from keepfold.vault import (
|
|
27
|
+
HEADING_RE,
|
|
28
|
+
ID_RE,
|
|
29
|
+
Note,
|
|
30
|
+
Vault,
|
|
31
|
+
VaultError,
|
|
32
|
+
_section,
|
|
33
|
+
is_private,
|
|
34
|
+
parse_error,
|
|
35
|
+
warm,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
GLYPHS = GLYPH # mcp_server imports this name
|
|
41
|
+
NOTE_KINDS = ("concept", "area", "domain", "mistake", "problem", "assessment", "application",
|
|
42
|
+
"resource", "note", "project", "decision", "journal", "loop")
|
|
43
|
+
STATE_KINDS = ("due", "weak", "ready")
|
|
44
|
+
EDGE_KEYS = ("parent", "areas", "requires", "related", "mistakes", "concepts", "tests", "covers",
|
|
45
|
+
"applies", "decisions", "project", "assessments", "application")
|
|
46
|
+
SNAPSHOT = ".keepfold/index-snapshot.json" # parsed notes keyed by (mtime_ns, size); JSON only
|
|
47
|
+
SNAPSHOT_SCHEMA = 1
|
|
48
|
+
SNAPSHOT_MIN = 50 # a refresh that parsed at least this many files saves the snapshot
|
|
49
|
+
MAX_HITS = 8
|
|
50
|
+
SNIPPET = 120
|
|
51
|
+
READ_CAP_CHARS = 1200 * 4 # ~1.2k tokens at chars/4
|
|
52
|
+
TRUNCATED = "\n[truncated]"
|
|
53
|
+
WINDOW_MIN = 200 # keepfold_read(window=): the smallest window, in characters
|
|
54
|
+
OUTLINE = 8 # headings a cut read lists of the rest
|
|
55
|
+
WIKILINK_RE = re.compile(r"^\[\[([^\]|#^]+)(?:[|#^][^\]]*)?\]\]$")
|
|
56
|
+
LINK_RE = re.compile(r"\[\[([^\]]+)\]\]") # a [[link]] anywhere in text
|
|
57
|
+
FENCE_RE = re.compile(r"^(```|~~~).*?^\1[^\n]*$", re.M | re.S)
|
|
58
|
+
# BM25 column weights (id, kind, title, aliases, headings, body): an alias is a name like the
|
|
59
|
+
# title (R13d), so it weighs the same
|
|
60
|
+
BM25 = "bm25(fts, 0, 0, 10, 10, 3, 1)"
|
|
61
|
+
|
|
62
|
+
SCHEMA = """
|
|
63
|
+
CREATE VIRTUAL TABLE fts USING fts5(id UNINDEXED, kind UNINDEXED, title, aliases, headings,
|
|
64
|
+
body, tokenize='unicode61 remove_diacritics 2');
|
|
65
|
+
CREATE TABLE nodes(id TEXT PRIMARY KEY, kind TEXT, title TEXT, parent TEXT, domain TEXT);
|
|
66
|
+
CREATE TABLE edges(src TEXT, dst TEXT, type TEXT);
|
|
67
|
+
CREATE INDEX edges_src ON edges(src);
|
|
68
|
+
CREATE INDEX edges_dst ON edges(dst);
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _plain(v):
|
|
73
|
+
"""ruamel values to JSON-safe Python values."""
|
|
74
|
+
if isinstance(v, Mapping):
|
|
75
|
+
return {str(k): _plain(x) for k, x in v.items()}
|
|
76
|
+
if isinstance(v, (list, tuple)):
|
|
77
|
+
return [_plain(x) for x in v]
|
|
78
|
+
if isinstance(v, (dt.date, dt.datetime)):
|
|
79
|
+
return v.isoformat()
|
|
80
|
+
if isinstance(v, bool) or v is None:
|
|
81
|
+
return v
|
|
82
|
+
if isinstance(v, int):
|
|
83
|
+
return int(v)
|
|
84
|
+
if isinstance(v, float):
|
|
85
|
+
return float(v)
|
|
86
|
+
return str(v)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _target(raw) -> str | None:
|
|
90
|
+
"""'[[x]]', 'x', 'concept:x', '[[x|label]]', '[[x#heading]]' or '[[x^block]]' to the id
|
|
91
|
+
'x'; None if it is not an id. The one link-target parser (audit F25)."""
|
|
92
|
+
s = str(raw).strip()
|
|
93
|
+
m = WIKILINK_RE.match(s)
|
|
94
|
+
if m:
|
|
95
|
+
s = m.group(1).strip()
|
|
96
|
+
s = s.split(":", 1)[1] if ":" in s else s
|
|
97
|
+
return s if ID_RE.fullmatch(s) else None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def link_targets(text: str) -> list[str]:
|
|
101
|
+
"""The ids of the [[links]] in `text`, in order, by `_target`'s rules."""
|
|
102
|
+
return [t for m in LINK_RE.finditer(text) if (t := _target(f"[[{m.group(1)}]]"))]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def aliases(fields: Mapping) -> list[str]:
|
|
106
|
+
"""A page's `aliases:` (Obsidian's convention: a YAML list or one string), stripped, empty
|
|
107
|
+
ones dropped. Untrusted note text, like a title."""
|
|
108
|
+
a = fields.get("aliases") or []
|
|
109
|
+
return [s for x in (a if isinstance(a, (list, tuple)) else [a])
|
|
110
|
+
if x is not None and (s := str(x).strip())]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _edge_targets(value) -> list[str]:
|
|
114
|
+
items = value.keys() if isinstance(value, Mapping) else \
|
|
115
|
+
value if isinstance(value, (list, tuple)) else [value]
|
|
116
|
+
return [t for t in (_target(x) for x in items if x is not None) if t]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
STOPWORDS = frozenset(
|
|
120
|
+
"a an and are as at be but by can do does for from how i in is it its me my of on or so "
|
|
121
|
+
"that the this to was what when where which who why will with you your".split())
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
_SYNTAX = re.compile(r'"([^"]*)"|(?<!\S)-(\w+)|(\w+)')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def fts_query(text: str, any_word: bool = False, syntax: bool = False) -> str:
|
|
128
|
+
"""User text to a safe MATCH string: each word a quoted prefix term, ANDed. `any_word` ORs
|
|
129
|
+
the words and drops stopwords instead. '' if none. With `syntax` (agent search, RR-33) a
|
|
130
|
+
"quoted span" is an exact phrase and a leading -word excludes that word; a query with no
|
|
131
|
+
positive term left, or one FTS5 refuses, falls back to the literal form."""
|
|
132
|
+
words = re.findall(r"\w+", text or "")
|
|
133
|
+
literal = " OR ".join(f'"{t}"*' for t in words if t.lower() not in STOPWORDS) if any_word \
|
|
134
|
+
else " ".join(f'"{t}"*' for t in words)
|
|
135
|
+
if not syntax or not any(c in (text or "") for c in '"-'):
|
|
136
|
+
return literal
|
|
137
|
+
pos, neg = [], []
|
|
138
|
+
for phrase, excl, word in _SYNTAX.findall(text):
|
|
139
|
+
if excl:
|
|
140
|
+
neg.append(f'"{excl}"')
|
|
141
|
+
elif word and not (any_word and word.lower() in STOPWORDS):
|
|
142
|
+
pos.append(f'"{word}"*')
|
|
143
|
+
elif toks := re.findall(r"\w+", phrase):
|
|
144
|
+
pos.append(f'"{" ".join(toks)}"')
|
|
145
|
+
if not pos:
|
|
146
|
+
return literal
|
|
147
|
+
q = (" OR " if any_word else " ").join(pos)
|
|
148
|
+
q = f"({q}) NOT ({' OR '.join(neg)})" if neg else q
|
|
149
|
+
return q if _fts_ok(q) else literal
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@functools.lru_cache(maxsize=256)
|
|
153
|
+
def _fts_ok(match: str) -> bool:
|
|
154
|
+
"""Does FTS5 parse `match`? Checked on an empty in-memory table."""
|
|
155
|
+
db = sqlite3.connect(":memory:")
|
|
156
|
+
try:
|
|
157
|
+
db.execute("CREATE VIRTUAL TABLE t USING fts5(a)")
|
|
158
|
+
db.execute("SELECT * FROM t WHERE t MATCH ?", (match,)).fetchall()
|
|
159
|
+
return True
|
|
160
|
+
except sqlite3.Error:
|
|
161
|
+
return False
|
|
162
|
+
finally:
|
|
163
|
+
db.close()
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# Look-alikes of an `untrusted_note` tag: each char's comparison key (NFKD, casefolded, marks,
|
|
167
|
+
# format/zero-width chars, controls, spaces, dashes and underscores dropped, homoglyphs folded)
|
|
168
|
+
# is matched after every `<`-like char, so `</ untrusted-n<U+200B><Cyrillic o>te` is a tag too.
|
|
169
|
+
# Code points, not literals, so no look-alike hides in this source.
|
|
170
|
+
_LT = "".join(map(chr, (0x3C, 0xAB, 0x2C2, 0x1438, 0x2039, 0x2329, 0x226E, 0x276E, 0x27E8,
|
|
171
|
+
0x3008, 0xFE3F, 0xFE64, 0xFF1C))) # every char keyed "<" (tested)
|
|
172
|
+
_LT_RE = re.compile(f"[{re.escape(_LT)}]")
|
|
173
|
+
_FOLD = str.maketrans({c: k for k, cs in { # Cyrillic, Greek, Armenian, small caps, digits
|
|
174
|
+
"<": tuple(map(ord, _LT)), "/": (0x5C, 0x2044, 0x2215, 0x2571, 0x29F8),
|
|
175
|
+
"a": (0x430,), "c": (0x441,), "d": (0x501, 0x1D05), "e": (0x435, 0x3B5, 0x1D07),
|
|
176
|
+
"i": (0x456, 0x3B9), "k": (0x43A, 0x3BA), "m": (0x43C,),
|
|
177
|
+
"n": (0x43F, 0x3B7, 0x3BD, 0x578, 0x274), "o": (0x43E, 0x3BF, 0x585, 0x1D0F, 0x30),
|
|
178
|
+
"p": (0x440, 0x3C1), "r": (0x433, 0x280), "s": (0x455, 0xA731, 0x35),
|
|
179
|
+
"t": (0x442, 0x3C4, 0x1D1B, 0x37), "u": (0x3C5, 0x3BC, 0x57D, 0x1D1C),
|
|
180
|
+
"x": (0x445, 0x3C7), "y": (0x443,),
|
|
181
|
+
"_": (0x2581,)}.items() for c in cs}) # DeepSeek's tokens (U+FF5C is "|" by NFKD)
|
|
182
|
+
_SKIP_CATS = {"Cc", "Cf", "Mn", "Me", "Pc", "Pd", "Zl", "Zp", "Zs"}
|
|
183
|
+
_BLANKS = set(map(chr, (0x115F, 0x1160, 0x2800, 0x3164, 0xFFA0))) # letters that render blank
|
|
184
|
+
_TAGS = ("untrustednote", "/untrustednote")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@functools.lru_cache(maxsize=4096)
|
|
188
|
+
def _key(ch: str) -> str:
|
|
189
|
+
return "".join(c for c in unicodedata.normalize("NFKD", ch).casefold().translate(_FOLD)
|
|
190
|
+
if c not in _BLANKS and unicodedata.category(c) not in _SKIP_CATS)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _tag_follows(text: str, j: int) -> bool:
|
|
194
|
+
"""Do the chars from `j` on spell `/?untrustednote` once compared by `_key`? Stops at the
|
|
195
|
+
first char that cannot continue it, so the scans from each `<` never overlap: linear."""
|
|
196
|
+
s = ""
|
|
197
|
+
while j < len(text):
|
|
198
|
+
s += _key(text[j])
|
|
199
|
+
j += 1
|
|
200
|
+
if s.startswith(_TAGS):
|
|
201
|
+
return True
|
|
202
|
+
if not any(t.startswith(s) for t in _TAGS):
|
|
203
|
+
return False
|
|
204
|
+
return False
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _neutralise(text: str) -> str:
|
|
208
|
+
"""Break every look-alike of an opening or closing `untrusted_note` tag: its `<` becomes
|
|
209
|
+
`<`, the rest of the text is left as it is."""
|
|
210
|
+
out, last = [], 0
|
|
211
|
+
for m in _LT_RE.finditer(text):
|
|
212
|
+
if _tag_follows(text, m.end()):
|
|
213
|
+
out += [text[last:m.start()], "<"]
|
|
214
|
+
last = m.end()
|
|
215
|
+
return "".join(out) + text[last:]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _wrap(id: str, text: str) -> str:
|
|
219
|
+
text = _neutralise(text)
|
|
220
|
+
return f'<untrusted_note id="{html.escape(id, quote=True)}">\n{text}\n</untrusted_note>'
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _preview(body: str) -> str:
|
|
224
|
+
return " ".join(ln for ln in body.splitlines() if not HEADING_RE.match(ln))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _offset(body: str, at) -> int:
|
|
228
|
+
"""RR-12: where `at` starts in a note body: an offset (an int or digits, moved back to
|
|
229
|
+
its line start when that is under WINDOW_MIN back) or a heading's text (with or without #s,
|
|
230
|
+
any case)."""
|
|
231
|
+
if isinstance(at, int) or str(at).strip().isdigit():
|
|
232
|
+
off = max(0, min(len(body), int(at)))
|
|
233
|
+
start = body.rfind("\n", 0, off) + 1
|
|
234
|
+
# a next_at cut mid-line is at least a window past its line start: snapping back
|
|
235
|
+
# to it would re-read the same text forever (audit 21 Nov C5)
|
|
236
|
+
return start if off - start < WINDOW_MIN else off
|
|
237
|
+
want = str(at).lstrip("#").strip().casefold()
|
|
238
|
+
pos = 0
|
|
239
|
+
for line in body.splitlines(keepends=True):
|
|
240
|
+
m = HEADING_RE.match(line.rstrip("\r\n"))
|
|
241
|
+
if m and m.group(2).casefold() == want:
|
|
242
|
+
return pos
|
|
243
|
+
pos += len(line)
|
|
244
|
+
raise VaultError("invalid_argument", f"Heading '{str(at)[:80]}' is not in the note; pass "
|
|
245
|
+
"an existing heading or an offset.")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _rest(body: str, cut: int) -> str:
|
|
249
|
+
"""RR-12: the end of a read cut at `cut`: how much is left and the rest's headings."""
|
|
250
|
+
heads = [ln.strip() for ln in body[cut:].splitlines() if HEADING_RE.match(ln)]
|
|
251
|
+
more = len(body.rstrip()) - cut
|
|
252
|
+
return (f"\n[truncated: {more:,} more characters"
|
|
253
|
+
+ ("; the rest's headings:]\n" + "\n".join(heads[:OUTLINE])
|
|
254
|
+
+ (f"\n(+{len(heads) - OUTLINE} more headings)" if len(heads) > OUTLINE else "")
|
|
255
|
+
if heads else "]"))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _one_line(text: str, n: int = SNIPPET) -> str:
|
|
259
|
+
s = " ".join(text.split())
|
|
260
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class Index:
|
|
264
|
+
def __init__(self, vault: Vault, catalog, states: Mapping[str, Any] | None = None,
|
|
265
|
+
withhold=None, save: bool = True):
|
|
266
|
+
self.vault = vault
|
|
267
|
+
self.save = save # False (the app's dry run): never write the snapshot
|
|
268
|
+
# (this index) -> ids kept out like hidden ones (so out of the snapshot too): a non-owner
|
|
269
|
+
# server's me/ pages not shared with work, a profile's out-of-scope playbooks
|
|
270
|
+
# (mcp_server.Keepfold._index_withheld)
|
|
271
|
+
self.withhold = withhold
|
|
272
|
+
self.catalog = catalog
|
|
273
|
+
self.states: Mapping[str, Any] = states or {}
|
|
274
|
+
self.day: str | None = None # local day `states` are as of, for find(kind="due")
|
|
275
|
+
# the server builds the index in a start-up thread, then uses it on the loop thread only
|
|
276
|
+
self.db = sqlite3.connect(":memory:", check_same_thread=False)
|
|
277
|
+
self.db.executescript(SCHEMA)
|
|
278
|
+
self._stats: dict = {} # path -> (mtime_ns, size)
|
|
279
|
+
# the last scan's str -> Path: a reused Path keeps its parsed parts and hash, which
|
|
280
|
+
# cost more than the scan itself to rebuild for every page on every call
|
|
281
|
+
self._paths: dict[str, Path] = {}
|
|
282
|
+
self._ids: dict = {} # path -> id it was indexed under
|
|
283
|
+
self._notes: dict[str, dict] = {} # id -> {kind, title, fields, body}
|
|
284
|
+
self._rowid: dict[str, int] = {} # id -> fts rowid: a delete by the UNINDEXED id scans
|
|
285
|
+
self._private: set[str] = set()
|
|
286
|
+
self._flagged: set[str] = set() # domains, areas, concepts with their own private: true
|
|
287
|
+
self._hidden: set[str] = set() # planner.hidden as of the last refresh
|
|
288
|
+
self._held: dict[str, Note] = {} # id -> its note, private only by `_hidden`: lifting
|
|
289
|
+
# that re-adds it from here, without a parse
|
|
290
|
+
# playbook id -> its own `scope:` (None: all), parsed even while hidden, so `withhold`
|
|
291
|
+
# can keep out the ones a client's profile does not allow (access.scope_own)
|
|
292
|
+
self.playbook_scopes: dict[str, object] = {}
|
|
293
|
+
self.dirty = False # the snapshot on disk is behind this index
|
|
294
|
+
self._snap = self._load_snapshot() # relpath -> entry; read by the first refresh only
|
|
295
|
+
self.refresh()
|
|
296
|
+
|
|
297
|
+
# ---- building ---------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
def _scan(self) -> dict:
|
|
300
|
+
out, known, self._paths = {}, self._paths, {}
|
|
301
|
+
for kind in self.vault.KIND_DIRS:
|
|
302
|
+
for e in self.vault.note_entries(kind):
|
|
303
|
+
if ID_RE.fullmatch(e.name[:-3]): # the stem: note_entries ends each in .md
|
|
304
|
+
try:
|
|
305
|
+
# the listing's own data on Windows (a tenth of a stat per file); a
|
|
306
|
+
# real stat on Linux and macOS.
|
|
307
|
+
# shortcut: a file still open for writing on Windows may show its old
|
|
308
|
+
# (mtime_ns, size) until it is closed; the first call after the close
|
|
309
|
+
# re-reads it. Upgrade to os.stat per file if a writer that keeps
|
|
310
|
+
# pages open appears.
|
|
311
|
+
st = e.stat()
|
|
312
|
+
except OSError:
|
|
313
|
+
continue
|
|
314
|
+
path = self._paths[e.path] = known.get(e.path) or Path(e.path)
|
|
315
|
+
out[path] = (kind, (st.st_mtime_ns, st.st_size))
|
|
316
|
+
return out
|
|
317
|
+
|
|
318
|
+
def refresh(self) -> int:
|
|
319
|
+
"""Re-index files whose (mtime_ns, size) changed, and drop deleted ones. Pages under a
|
|
320
|
+
private domain or area count as private (planner.hidden, the views' rule)."""
|
|
321
|
+
self._parsed = 0
|
|
322
|
+
n = self._refresh()
|
|
323
|
+
if self._snap: # entries for files that are gone
|
|
324
|
+
self.dirty = True
|
|
325
|
+
self._snap = {}
|
|
326
|
+
if self._parsed >= SNAPSHOT_MIN:
|
|
327
|
+
self.save_snapshot()
|
|
328
|
+
return n
|
|
329
|
+
|
|
330
|
+
def _refresh(self) -> int:
|
|
331
|
+
from keepfold import planner # lazy: planner imports catalog, which imports this module
|
|
332
|
+
|
|
333
|
+
seen = self._scan()
|
|
334
|
+
n = 0
|
|
335
|
+
fresh = [p for p, (_, st) in seen.items()
|
|
336
|
+
if self._stats.get(p) != st and self._rel(p) not in self._snap]
|
|
337
|
+
if len(fresh) > 32: # a build, not a one-file refresh: open them side by side first
|
|
338
|
+
warm(fresh)
|
|
339
|
+
with self.db:
|
|
340
|
+
for path in [p for p in self._stats if p not in seen]:
|
|
341
|
+
self._drop(self._ids.pop(path, None))
|
|
342
|
+
del self._stats[path]
|
|
343
|
+
self.dirty = True
|
|
344
|
+
n += 1
|
|
345
|
+
for path, (kind, stat) in seen.items():
|
|
346
|
+
if self._stats.get(path) == stat:
|
|
347
|
+
continue
|
|
348
|
+
self._drop(self._ids.pop(path, None))
|
|
349
|
+
self._stats[path] = stat
|
|
350
|
+
n += 1
|
|
351
|
+
note = self._from_snapshot(path, kind, stat)
|
|
352
|
+
if note is None:
|
|
353
|
+
self._parsed += 1
|
|
354
|
+
self.dirty = True
|
|
355
|
+
try:
|
|
356
|
+
note = self._parse(path, kind)
|
|
357
|
+
except Exception as e: # YAML, fence, encoding or containment errors
|
|
358
|
+
log.warning("not indexing %s: %s", path, parse_error(e))
|
|
359
|
+
continue
|
|
360
|
+
self._ids[path] = note.id
|
|
361
|
+
self._add(note)
|
|
362
|
+
# From the flags just indexed, not a second vault walk: that would cost ~3x per refresh.
|
|
363
|
+
hidden = planner.hidden(self.vault, self.catalog, self._flagged) | (
|
|
364
|
+
self.withhold(self) if self.withhold else set())
|
|
365
|
+
if hidden != self._hidden: # privacy inherited or lifted: re-add those pages once
|
|
366
|
+
changed = hidden ^ self._hidden
|
|
367
|
+
self._hidden, self.dirty = hidden, True # hidden pages stay out of the snapshot
|
|
368
|
+
with self.db: # from the rows already parsed, not the files: a withhold switch
|
|
369
|
+
for path, id in self._ids.items(): # (the X-ray's dry runs) flips thousands
|
|
370
|
+
if id not in changed or id in self._flagged: # flagged stay private anyway
|
|
371
|
+
continue
|
|
372
|
+
if (note := self._held.get(id)) is None and (e := self._notes.get(id)):
|
|
373
|
+
# the snapshot's own form of a page (its _snapshot_data row)
|
|
374
|
+
note = Note(path, e["kind"], id, e["fields"], e["body"])
|
|
375
|
+
if note is not None: # else its own private: true keeps it private anyway
|
|
376
|
+
self._add(note)
|
|
377
|
+
n += 1
|
|
378
|
+
return n
|
|
379
|
+
|
|
380
|
+
# ---- snapshot -----------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
@property
|
|
383
|
+
def snapshot_path(self) -> Path:
|
|
384
|
+
return self.vault.root / SNAPSHOT
|
|
385
|
+
|
|
386
|
+
@staticmethod
|
|
387
|
+
def _rel(path) -> str:
|
|
388
|
+
# _scan paths are always <root>/<kind folder>/<id>.md; pathlib.relative_to cost ~1 s
|
|
389
|
+
return f"{path.parent.name}/{path.name}"
|
|
390
|
+
|
|
391
|
+
def _load_snapshot(self) -> dict:
|
|
392
|
+
p = self.snapshot_path
|
|
393
|
+
if not p.is_file():
|
|
394
|
+
return {}
|
|
395
|
+
try:
|
|
396
|
+
data = json.loads(p.read_bytes()) # JSON, never pickle: loading runs no vault code
|
|
397
|
+
if data.get("schema") != SNAPSHOT_SCHEMA or not isinstance(data.get("files"), dict):
|
|
398
|
+
raise ValueError(f"schema {data.get('schema')!r}, want {SNAPSHOT_SCHEMA}")
|
|
399
|
+
return data["files"]
|
|
400
|
+
except (OSError, ValueError, AttributeError) as e:
|
|
401
|
+
log.warning("index snapshot ignored, rebuilding it: %s", e)
|
|
402
|
+
self.dirty = True
|
|
403
|
+
return {}
|
|
404
|
+
|
|
405
|
+
def _from_snapshot(self, path, kind: str, stat) -> Note | None:
|
|
406
|
+
"""The note as the snapshot holds it when its (mtime_ns, size) still match; else None.
|
|
407
|
+
A private entry has no fields or body: it only marks the id private (and flagged)."""
|
|
408
|
+
e = self._snap.pop(self._rel(path), None)
|
|
409
|
+
if not (isinstance(e, list) and len(e) in (5, 6) and e[:2] == list(stat)
|
|
410
|
+
and e[2] == kind and e[3] == path.stem and isinstance(e[4], dict)):
|
|
411
|
+
return None
|
|
412
|
+
if len(e) == 5:
|
|
413
|
+
return Note(path, kind, path.stem, {"private": True}, "") \
|
|
414
|
+
if e[4].get("private") is True else None
|
|
415
|
+
return Note(path, kind, path.stem, e[4], e[5]) if isinstance(e[5], str) else None
|
|
416
|
+
|
|
417
|
+
def _snapshot_data(self) -> dict:
|
|
418
|
+
kinds = {d: k for k, d in self.vault.KIND_DIRS.items()}
|
|
419
|
+
files = {}
|
|
420
|
+
for path, id in self._ids.items():
|
|
421
|
+
stat, n = self._stats.get(path), self._notes.get(id)
|
|
422
|
+
# a browse site page sits in browse/sites/<category>/: its kind is the parsed one
|
|
423
|
+
kind = kinds.get(path.parent.name) or (n["kind"] if n else None)
|
|
424
|
+
if stat is None:
|
|
425
|
+
continue
|
|
426
|
+
if n is not None and n["kind"] == kind:
|
|
427
|
+
files[self._rel(path)] = [*stat, kind, id, n["fields"], n["body"]]
|
|
428
|
+
# Own private: true only. Pages private by inheritance (planner.hidden) are left
|
|
429
|
+
# out and reparsed, so lifting the parent's flag brings them back in full.
|
|
430
|
+
elif id in self._private and (id not in self._hidden or id in self._flagged):
|
|
431
|
+
files[self._rel(path)] = [*stat, kind, id,
|
|
432
|
+
{"private": True, "flagged": id in self._flagged}]
|
|
433
|
+
return {"schema": SNAPSHOT_SCHEMA, "files": files}
|
|
434
|
+
|
|
435
|
+
def save_snapshot(self) -> None:
|
|
436
|
+
"""Write the snapshot under the vault lock; a failure only logs (the next build redoes
|
|
437
|
+
the parse)."""
|
|
438
|
+
if not self.save:
|
|
439
|
+
return
|
|
440
|
+
try:
|
|
441
|
+
with self.vault.lock(): # the lock creates .keepfold/
|
|
442
|
+
self.vault.write_text(self.snapshot_path,
|
|
443
|
+
json.dumps(self._snapshot_data(), ensure_ascii=False))
|
|
444
|
+
self.dirty = False
|
|
445
|
+
except (VaultError, OSError) as e:
|
|
446
|
+
log.warning("index snapshot not saved: %s", e)
|
|
447
|
+
|
|
448
|
+
def _parse(self, path, kind: str) -> Note:
|
|
449
|
+
# The vault's cached parse: the planner and levels then reuse these notes for free.
|
|
450
|
+
return self.vault._parse(self.vault._contained(path), kind)
|
|
451
|
+
|
|
452
|
+
def _drop(self, id: str | None) -> None:
|
|
453
|
+
if id is None:
|
|
454
|
+
return
|
|
455
|
+
self._private.discard(id)
|
|
456
|
+
self._held.pop(id, None)
|
|
457
|
+
self._flagged.discard(id)
|
|
458
|
+
self.playbook_scopes.pop(id, None)
|
|
459
|
+
self._notes.pop(id, None)
|
|
460
|
+
if (rowid := self._rowid.pop(id, None)) is not None:
|
|
461
|
+
self.db.execute("DELETE FROM fts WHERE rowid = ?", (rowid,))
|
|
462
|
+
self.db.execute("DELETE FROM nodes WHERE id = ?", (id,))
|
|
463
|
+
self.db.execute("DELETE FROM edges WHERE src = ?", (id,))
|
|
464
|
+
|
|
465
|
+
def _add(self, note) -> None:
|
|
466
|
+
# Invariant: ids are unique across kinds (Vault.create_note refuses a clash and
|
|
467
|
+
# `keepfold doctor` lists hand-made ones), so keying nodes by id alone is safe.
|
|
468
|
+
if note.id in self._notes or note.id in self._private: # a fresh build drops nothing
|
|
469
|
+
self._drop(note.id)
|
|
470
|
+
if is_private(note) and note.kind in ("domain", "area", "concept"):
|
|
471
|
+
self._flagged.add(note.id)
|
|
472
|
+
tags = note.fields.get("tags") # prime.PLAYBOOK_TAG; kept for hidden pages too
|
|
473
|
+
if note.kind == "note" and "playbook" in (tags if isinstance(tags, list) else [tags]):
|
|
474
|
+
self.playbook_scopes[note.id] = note.fields.get("scope")
|
|
475
|
+
else:
|
|
476
|
+
self.playbook_scopes.pop(note.id, None)
|
|
477
|
+
if is_private(note) or note.id in self._hidden:
|
|
478
|
+
self._private.add(note.id)
|
|
479
|
+
if not is_private(note):
|
|
480
|
+
self._held[note.id] = note
|
|
481
|
+
return
|
|
482
|
+
f = note.fields
|
|
483
|
+
headings = [m.group(2) for line in note.body.splitlines()
|
|
484
|
+
if (m := HEADING_RE.match(line))]
|
|
485
|
+
title = str(f.get("title") or (headings[0] if headings else note.id))
|
|
486
|
+
entry = getattr(self.catalog, "entries", {}).get(note.id)
|
|
487
|
+
parent = (_edge_targets(f["parent"]) or [None])[0] if f.get("parent") else \
|
|
488
|
+
(entry.parent if entry else None)
|
|
489
|
+
domain = str(f.get("domain") or (entry.domain if entry else "") or "")
|
|
490
|
+
self._notes[note.id] = {"kind": note.kind, "title": title, "fields": _plain(f),
|
|
491
|
+
"body": note.body}
|
|
492
|
+
self._rowid[note.id] = self.db.execute(
|
|
493
|
+
"INSERT INTO fts VALUES (?, ?, ?, ?, ?, ?)",
|
|
494
|
+
(note.id, note.kind, title, " ".join(aliases(f)), " ".join(headings),
|
|
495
|
+
note.body)).lastrowid
|
|
496
|
+
self.db.execute("INSERT INTO nodes VALUES (?, ?, ?, ?, ?)",
|
|
497
|
+
(note.id, note.kind, title, parent, domain))
|
|
498
|
+
edges = {(t, key) for key in EDGE_KEYS if f.get(key) is not None
|
|
499
|
+
for t in _edge_targets(f[key])}
|
|
500
|
+
# Body [[links]] are `mentions` edges for every kind (RETR-6). Journals keep their old
|
|
501
|
+
# rule exactly; other kinds skip code fences and targets a frontmatter edge already has.
|
|
502
|
+
journal = note.kind == "journal"
|
|
503
|
+
body = note.body if journal else FENCE_RE.sub("", note.body)
|
|
504
|
+
typed = set() if journal else {t for t, _ in edges}
|
|
505
|
+
edges |= {(t, "mentions") for t in link_targets(body) if t not in typed}
|
|
506
|
+
self.db.executemany("INSERT INTO edges VALUES (?, ?, ?)",
|
|
507
|
+
[(note.id, t, key) for t, key in sorted(edges)])
|
|
508
|
+
|
|
509
|
+
# ---- states -----------------------------------------------------------
|
|
510
|
+
|
|
511
|
+
def _state(self, id: str) -> str:
|
|
512
|
+
return getattr(self.states.get(id), "state", None) or "not_started"
|
|
513
|
+
|
|
514
|
+
def _hit(self, id: str, kind: str, title: str, snippet: str) -> dict:
|
|
515
|
+
state = self._state(id) if kind == "concept" else None
|
|
516
|
+
summary = self._notes[id]["fields"].get("summary")
|
|
517
|
+
return {"id": id, "kind": kind, "title": title,
|
|
518
|
+
**({"summary": _one_line(str(summary))} if summary else {}),
|
|
519
|
+
"state": state, "glyph": GLYPH.get(state, ""), "snippet": _one_line(snippet)}
|
|
520
|
+
|
|
521
|
+
def _state_ids(self, kind: str) -> list[str]:
|
|
522
|
+
concepts = [r[0] for r in self.db.execute(
|
|
523
|
+
"SELECT id FROM nodes WHERE kind = 'concept' ORDER BY id")]
|
|
524
|
+
from keepfold import planner # lazy: planner imports catalog, which imports this module
|
|
525
|
+
if kind == "due":
|
|
526
|
+
from keepfold.events import local_day
|
|
527
|
+
day = self.day or local_day(dt.datetime.now(dt.UTC))
|
|
528
|
+
due = [c for c in concepts if planner.is_due(self.states.get(c), day)]
|
|
529
|
+
nd = {c: getattr(self.states.get(c), "next_due", None) for c in due}
|
|
530
|
+
return sorted(due, key=lambda c: (nd[c] is None, str(nd[c] or "")))
|
|
531
|
+
if kind == "weak":
|
|
532
|
+
return [c for c in concepts if self._state(c) == "learning"
|
|
533
|
+
or getattr(self.states.get(c), "open_mistakes", None)]
|
|
534
|
+
|
|
535
|
+
def requires(c):
|
|
536
|
+
return SimpleNamespace(requires=[r[0] for r in self.db.execute(
|
|
537
|
+
"SELECT dst FROM edges WHERE src = ? AND type = 'requires'", (c,))])
|
|
538
|
+
|
|
539
|
+
return [c for c in concepts
|
|
540
|
+
if planner.is_ready(self._state(c), requires(c), self.states)]
|
|
541
|
+
|
|
542
|
+
# ---- find -------------------------------------------------------------
|
|
543
|
+
|
|
544
|
+
def find(self, query: str = "", kind: str | None = None, limit: int = MAX_HITS,
|
|
545
|
+
any_word: bool = False, keep=None,
|
|
546
|
+
syntax: bool = False) -> list[dict]:
|
|
547
|
+
"""FTS hits, or a state list; `keep(id)` (a date or source filter) is applied before
|
|
548
|
+
the limit."""
|
|
549
|
+
if kind is not None and kind not in NOTE_KINDS + STATE_KINDS:
|
|
550
|
+
raise VaultError("invalid_argument", f"kind must be one of "
|
|
551
|
+
f"{', '.join(NOTE_KINDS + STATE_KINDS)}.")
|
|
552
|
+
try:
|
|
553
|
+
limit = max(1, min(MAX_HITS, int(limit)))
|
|
554
|
+
except (TypeError, ValueError):
|
|
555
|
+
limit = MAX_HITS
|
|
556
|
+
match = fts_query(query, any_word, syntax)
|
|
557
|
+
if kind in STATE_KINDS:
|
|
558
|
+
ids = self._state_ids(kind)
|
|
559
|
+
if match:
|
|
560
|
+
ranked = {r[0]: r[1] for r in self.db.execute(
|
|
561
|
+
"SELECT id, snippet(fts, 5, '', '', '…', 16) FROM fts WHERE fts MATCH ? "
|
|
562
|
+
"AND kind = 'concept'", (match,))}
|
|
563
|
+
ids = [i for i in ids if i in ranked]
|
|
564
|
+
ids = [i for i in ids if keep is None or keep(i)]
|
|
565
|
+
hits = []
|
|
566
|
+
for i in ids[:limit]:
|
|
567
|
+
n = self._notes[i]
|
|
568
|
+
hits.append(self._hit(i, n["kind"], n["title"],
|
|
569
|
+
ranked[i] if match else _preview(n["body"])))
|
|
570
|
+
return hits
|
|
571
|
+
if not match:
|
|
572
|
+
return []
|
|
573
|
+
sql = ("SELECT id, kind, title, snippet(fts, 5, '', '', '…', 16) FROM fts "
|
|
574
|
+
"WHERE fts MATCH ?" + (" AND kind = ?" if kind else "") +
|
|
575
|
+
f" ORDER BY {BM25}")
|
|
576
|
+
if keep is None:
|
|
577
|
+
sql += " LIMIT ?"
|
|
578
|
+
args = (match, kind) if kind else (match,)
|
|
579
|
+
rows = self.db.execute(sql, (*args, limit) if keep is None else args)
|
|
580
|
+
return [self._hit(*row) for row in itertools.islice(
|
|
581
|
+
(r for r in rows if keep is None or keep(r[0])), limit)]
|
|
582
|
+
|
|
583
|
+
def problems(self, query: str = "", limit: int = MAX_HITS, syntax: bool = False
|
|
584
|
+
) -> list[dict]:
|
|
585
|
+
"""Problems, todo first, then attempted, then solved. A query keeps the problems whose
|
|
586
|
+
own text matches or that link a concept (`concepts:`) whose title or id matches."""
|
|
587
|
+
ids = [i for i, n in self._notes.items() if n["kind"] == "problem"]
|
|
588
|
+
if match := fts_query(query, syntax=syntax):
|
|
589
|
+
hit = {r[0] for r in self.db.execute(
|
|
590
|
+
"SELECT id FROM fts WHERE fts MATCH ? AND kind = 'problem'", (match,))}
|
|
591
|
+
hit |= {r[0] for r in self.db.execute( # concepts by title, not body
|
|
592
|
+
"SELECT id FROM fts WHERE fts MATCH ? AND kind = 'concept'",
|
|
593
|
+
(f"{{title aliases}} : ({match})",))}
|
|
594
|
+
words = [w.lower() for w in re.findall(r"\w+", query)]
|
|
595
|
+
ids = [i for i in ids if i in hit or any(
|
|
596
|
+
t in hit or all(w in t for w in words) for (t,) in self.db.execute(
|
|
597
|
+
"SELECT dst FROM edges WHERE src = ? AND type = 'concepts'", (i,)))]
|
|
598
|
+
rank = {"todo": 0, "attempted": 1, "solved": 2}
|
|
599
|
+
ids.sort(key=lambda i: (rank.get(self._notes[i]["fields"].get("status"), 1), i))
|
|
600
|
+
return [{**self._hit(i, "problem", self._notes[i]["title"], ""),
|
|
601
|
+
"status": self._notes[i]["fields"].get("status")} for i in ids[:limit]]
|
|
602
|
+
|
|
603
|
+
def title_matches(self, title: str, kind: str | None, limit: int = 3) -> list[str]:
|
|
604
|
+
"""Ids of `kind` (None: any kind) whose title or aliases hold every word of `title`
|
|
605
|
+
(prefix, any case); bodies are not searched, so a note that merely mentions the words
|
|
606
|
+
is no match."""
|
|
607
|
+
match = fts_query(title)
|
|
608
|
+
if not match:
|
|
609
|
+
return []
|
|
610
|
+
return [r[0] for r in self.db.execute(
|
|
611
|
+
"SELECT id FROM fts WHERE fts MATCH ?" + (" AND kind = ?" if kind else "")
|
|
612
|
+
+ f" ORDER BY {BM25} LIMIT ?",
|
|
613
|
+
(f"{{title aliases}} : ({match})", *([kind] if kind else []), limit))]
|
|
614
|
+
|
|
615
|
+
def related(self, query: str, limit: int = 5) -> list[dict]:
|
|
616
|
+
"""FTS hits on `query`, then one graph hop around the top three; any kind, no private."""
|
|
617
|
+
hits = self.find(query, None, MAX_HITS)
|
|
618
|
+
seen = {h["id"] for h in hits}
|
|
619
|
+
for h in hits[:3]:
|
|
620
|
+
for (i,) in self.db.execute(
|
|
621
|
+
"SELECT dst FROM edges WHERE src = ?1 UNION SELECT src FROM edges "
|
|
622
|
+
"WHERE dst = ?1", (h["id"],)):
|
|
623
|
+
if i not in seen and i in self._notes:
|
|
624
|
+
seen.add(i)
|
|
625
|
+
n = self._notes[i]
|
|
626
|
+
hits.append(self._hit(i, n["kind"], n["title"], ""))
|
|
627
|
+
return hits[:limit]
|
|
628
|
+
|
|
629
|
+
# ---- read -------------------------------------------------------------
|
|
630
|
+
|
|
631
|
+
def _resolve(self, id: str) -> str:
|
|
632
|
+
if id in self._notes:
|
|
633
|
+
return id
|
|
634
|
+
kinds = ("domain", "area", "concept")
|
|
635
|
+
try:
|
|
636
|
+
r = self.catalog.resolve(id, kinds)
|
|
637
|
+
if r in self._notes:
|
|
638
|
+
return r
|
|
639
|
+
except VaultError:
|
|
640
|
+
pass
|
|
641
|
+
raise VaultError("unknown_id", f"No note '{id}'; check the id with find.",
|
|
642
|
+
[s for s in self.catalog.suggest(id, kinds) if s in self._notes])
|
|
643
|
+
|
|
644
|
+
def _ids_where(self, sql: str, *args) -> list[str]:
|
|
645
|
+
return [r[0] for r in self.db.execute(sql, args) if r[0] not in self._private]
|
|
646
|
+
|
|
647
|
+
def linked_mistakes(self, id: str) -> list[str]:
|
|
648
|
+
"""Ids the note's `mistakes:` names, then mistake notes whose `concepts:` name it."""
|
|
649
|
+
mistakes = self._ids_where("SELECT dst FROM edges WHERE src = ? AND type = ?",
|
|
650
|
+
id, "mistakes")
|
|
651
|
+
return mistakes + [m for m in self._ids_where(
|
|
652
|
+
"SELECT e.src FROM edges e JOIN nodes n ON n.id = e.src "
|
|
653
|
+
"WHERE e.dst = ? AND e.type = ? AND n.kind = ?", id, "concepts", "mistake")
|
|
654
|
+
if m not in mistakes]
|
|
655
|
+
|
|
656
|
+
def read(self, id: str, sections: list[str] | None = None, at: int | str | None = None,
|
|
657
|
+
window: int | None = None) -> dict:
|
|
658
|
+
"""A note within READ_CAP_CHARS. `at` (an offset in the body, or a heading) and
|
|
659
|
+
`window` (characters) read a part of it (RR-12). A read cut short ends with the rest's
|
|
660
|
+
headings and gives `next_at`, the offset to read on from (not for `sections`)."""
|
|
661
|
+
id = self._resolve(str(id))
|
|
662
|
+
n = self._notes[id]
|
|
663
|
+
body = n["body"]
|
|
664
|
+
end = len(body.rstrip())
|
|
665
|
+
lo = None # where the shown text starts in the body; None for sections
|
|
666
|
+
if sections:
|
|
667
|
+
if at is not None or window is not None:
|
|
668
|
+
raise VaultError("invalid_argument", "Pass sections, or at/window, not both.")
|
|
669
|
+
lines = body.splitlines(keepends=True)
|
|
670
|
+
parts = []
|
|
671
|
+
for h in sections:
|
|
672
|
+
start, stop = _section(lines, h)
|
|
673
|
+
parts.append("".join(lines[start - 1 : stop]).rstrip())
|
|
674
|
+
text = "\n\n".join(parts)
|
|
675
|
+
else:
|
|
676
|
+
lo = _offset(body, at) if at is not None else len(body) - len(body.lstrip())
|
|
677
|
+
hi = end
|
|
678
|
+
if window is not None:
|
|
679
|
+
try:
|
|
680
|
+
size = max(WINDOW_MIN, min(READ_CAP_CHARS, int(window)))
|
|
681
|
+
except (TypeError, ValueError):
|
|
682
|
+
raise VaultError("invalid_argument", "window must be a number of "
|
|
683
|
+
"characters.") from None
|
|
684
|
+
if lo + size < end: # end at a line end when one is in the window's second half
|
|
685
|
+
nl = body.rfind("\n", lo + size // 2, lo + size)
|
|
686
|
+
hi = nl + 1 if nl > 0 else lo + size # the newline too: next_at starts a line
|
|
687
|
+
text = body[lo:hi]
|
|
688
|
+
# shown first, so the cap never cuts it; a later window of the page goes without
|
|
689
|
+
head = f"Summary: {n['fields']['summary']}\n\n" if n["fields"].get("summary") \
|
|
690
|
+
and at is None else ""
|
|
691
|
+
out_of = "SELECT dst FROM edges WHERE src = ? AND type = ?"
|
|
692
|
+
into = "SELECT e.src FROM edges e JOIN nodes n ON n.id = e.src " \
|
|
693
|
+
"WHERE e.dst = ? AND e.type = ? AND n.kind = ?"
|
|
694
|
+
parent = self.db.execute("SELECT parent FROM nodes WHERE id = ?", (id,)).fetchone()[0]
|
|
695
|
+
mistakes = self.linked_mistakes(id)
|
|
696
|
+
st = self.states.get(id)
|
|
697
|
+
next_due = getattr(st, "next_due", None)
|
|
698
|
+
result = {
|
|
699
|
+
"id": id, "kind": n["kind"], "title": n["title"],
|
|
700
|
+
"state": self._state(id) if n["kind"] == "concept" else None,
|
|
701
|
+
"fields": {k: v for k, v in n["fields"].items() if not k.startswith("keepfold_")},
|
|
702
|
+
"text": "",
|
|
703
|
+
"neighbours": {
|
|
704
|
+
"parent": parent if parent not in self._private else None,
|
|
705
|
+
"requires": self._ids_where(out_of, id, "requires"),
|
|
706
|
+
"required_by": self._ids_where(into, id, "requires", "concept"),
|
|
707
|
+
"mistakes": mistakes,
|
|
708
|
+
"problems": self._ids_where(into, id, "concepts", "problem"),
|
|
709
|
+
},
|
|
710
|
+
"open_mistakes": [str(m) for m in getattr(st, "open_mistakes", None) or []],
|
|
711
|
+
"next_refresh": _plain(next_due) if next_due is not None else None,
|
|
712
|
+
}
|
|
713
|
+
def show(shown: str, cut: bool) -> int:
|
|
714
|
+
"""Set the text and `next_at`; returns the JSON size over the cap."""
|
|
715
|
+
nxt = None if lo is None or not (cut or lo + len(shown) < end) else lo + len(shown)
|
|
716
|
+
rest = _rest(body, nxt) if nxt is not None else TRUNCATED if cut else ""
|
|
717
|
+
result["text"] = _wrap(id, head + shown.rstrip() + rest)
|
|
718
|
+
result.pop("next_at", None)
|
|
719
|
+
if nxt is not None:
|
|
720
|
+
result["next_at"] = nxt
|
|
721
|
+
return len(json.dumps(result, ensure_ascii=False)) - READ_CAP_CHARS
|
|
722
|
+
|
|
723
|
+
over = show(text, False)
|
|
724
|
+
while over > 0 and text:
|
|
725
|
+
# JSON escapes make the size non-linear in the cut, so trim until it fits, at a
|
|
726
|
+
# line end when one is in the kept half (the next read starts on a whole line);
|
|
727
|
+
# halved while far over, since escapes make `over` count more than the text holds
|
|
728
|
+
text = text[: len(text) // 2 if over > len(text) // 2
|
|
729
|
+
else max(0, len(text) - over - len(TRUNCATED))]
|
|
730
|
+
nl = text.rfind("\n")
|
|
731
|
+
text = text[:nl + 1] if nl > len(text) // 2 else text
|
|
732
|
+
over = show(text, True)
|
|
733
|
+
return result
|