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/safety_net.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
"""The chat safety net (`keepfold safety-net`, the app after each chat import): record what a chat
|
|
2
|
+
model forgot to log, from the chat pages already in the vault (chat_import).
|
|
3
|
+
|
|
4
|
+
A pass looks at chat pages (semantic.is_chat with `**Me:**` turns; coding summaries hold no
|
|
5
|
+
teaching and are left out) that are new or changed since the last pass. STATE (JSON under
|
|
6
|
+
`.keepfold/`, a git-ignored cache) keeps per resource page its (mtime_ns, size), the body hash
|
|
7
|
+
(chat_import._hash) and what was done, so a pass with nothing new only stats files.
|
|
8
|
+
|
|
9
|
+
A chat is skipped when:
|
|
10
|
+
- it is private (`private: true`, or its category is not "cloud" in the browse privacy
|
|
11
|
+
settings, as chat_import judges it); private chats never touch or create public pages;
|
|
12
|
+
- its last turn is older than RECENT_DAYS (a first pass must not mark old chats taught today);
|
|
13
|
+
- one of its names matches a hidden concept (planner.hidden): the chat is about a private
|
|
14
|
+
subject, so nothing public is written from it.
|
|
15
|
+
|
|
16
|
+
What the chat model already logged for a chat is never logged again: any live `ask`, `grade`
|
|
17
|
+
or `taught` event, or a `touch`, `taught` or `self_report` log, not written by this module or
|
|
18
|
+
an import, whose `ts` falls between the chat's first turn less BEFORE and its last turn plus
|
|
19
|
+
AFTER (turn times are the page's `### YYYY-MM-DD HH:MM` lines; a page with none uses its local
|
|
20
|
+
day). Live MCP logging carries no chat id, so the time span is the link. The ids those events
|
|
21
|
+
name are left out of both layers; the rest of the chat is still recorded.
|
|
22
|
+
|
|
23
|
+
Layer 1 (code only, always): concept titles and aliases (catalog) and topic hub titles and
|
|
24
|
+
aliases (the index) found as whole words in the user's turns, plus the hub `topics.attach`
|
|
25
|
+
picks for the chat's vector (FLOOR) when an embedder is already in memory. The new ids become one
|
|
26
|
+
`touch` log (no object: levels ignore it), each page at most once per chat.
|
|
27
|
+
|
|
28
|
+
Layer 2 (only with a runner whose model is already loaded; the app also needs the PC idle,
|
|
29
|
+
browse.titles.may_run): the model names at most PER_CHAT concepts the chat explained (JSON,
|
|
30
|
+
strict parse; junk, generic words and secrets refused, and a word of the name must occur in
|
|
31
|
+
the chat). Each goes through `Linker` (shared with keepfold_log taught/self_report and the
|
|
32
|
+
concepts of an assessment or problem): it resolves to an existing concept (catalog id, title,
|
|
33
|
+
alias or slug; then an embedding cosine >= MATCH_COS to a concept page; then the catalog's
|
|
34
|
+
near-duplicate "did you mean") or is created like keepfold_add (Catalog.add) under the area most
|
|
35
|
+
of the matched concepts share, else the area most concepts filed under the name's hub share,
|
|
36
|
+
else DOMAIN > AREA, and linked (`related`) to the hub `topics.attach` picks for its name. A
|
|
37
|
+
name matching a hidden concept never resolves or creates. Each gets one `taught` event per
|
|
38
|
+
chat, at most TAUGHT_PER_DAY a Keepfold day across chats (counted from the day's live events); a
|
|
39
|
+
chat a pass reaches after the cap gets layer 1 only (no model call, no new concept; its
|
|
40
|
+
touches are not capped by it).
|
|
41
|
+
|
|
42
|
+
Every event this writes has source SOURCE (server-stamped, never model output), session
|
|
43
|
+
`import` and payload {"auto": SOURCE, "chat": <page id>}. Caps: MAX_CHATS chats and MAX_EVENTS
|
|
44
|
+
events per pass. A pass that wrote something adds one journal line (the home feed). `undo`
|
|
45
|
+
voids the events (all, or one chat's); `keepfold void <event id>` voids one. Concepts it created
|
|
46
|
+
stay; merge or delete them by hand (`keepfold concept merge`).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import json
|
|
52
|
+
import logging
|
|
53
|
+
import re
|
|
54
|
+
from collections import Counter
|
|
55
|
+
from contextlib import nullcontext
|
|
56
|
+
from dataclasses import dataclass
|
|
57
|
+
from datetime import UTC, datetime, timedelta
|
|
58
|
+
|
|
59
|
+
from keepfold import chat_import, localllm, planner, topics
|
|
60
|
+
from keepfold.catalog import Catalog, page_slug, slugify
|
|
61
|
+
from keepfold.events import EventLog, live, local_day, parse_ts, void_event
|
|
62
|
+
from keepfold.index import STOPWORDS, Index
|
|
63
|
+
from keepfold.vault import Vault, VaultError, is_private, secret_pattern
|
|
64
|
+
|
|
65
|
+
log = logging.getLogger(__name__)
|
|
66
|
+
|
|
67
|
+
STATE, LOCK = ".keepfold/safety-net.json", ".keepfold/safety-net.lock"
|
|
68
|
+
BUSY = "A safety-net pass is already running."
|
|
69
|
+
SOURCE = "safety_net"
|
|
70
|
+
MAX_CHATS, MAX_EVENTS, PER_CHAT = 10, 15, 3 # per pass, per pass, model concepts per chat
|
|
71
|
+
TAUGHT_PER_DAY = 2 # layer-2 `taught` events per Keepfold day (04:00), across chats and passes
|
|
72
|
+
TOUCHES = 5 # ids in one touch event, as keepfold_log's TOUCH_MAX
|
|
73
|
+
RECENT_DAYS = 7
|
|
74
|
+
BEFORE, AFTER = timedelta(minutes=2), timedelta(minutes=30) # around the chat's turn times
|
|
75
|
+
# bge-small cosine of a short concept name to a concept page's head: near-synonyms score
|
|
76
|
+
# 0.85-0.95, related but different concepts 0.70-0.82
|
|
77
|
+
MATCH_COS = 0.85
|
|
78
|
+
EMBED_CHARS, MODEL_CHARS = 1500, 3000
|
|
79
|
+
NAME_CHARS, NAME_WORDS, MIN_NAME = 60, 6, 4
|
|
80
|
+
DOMAIN, AREA = "From chats", "Unsorted" # where a new concept goes when the chat has no area
|
|
81
|
+
LEARNING = ("ask", "grade", "taught") # event kinds
|
|
82
|
+
LEARNING_LOGS = ("touch", "taught", "self_report") # log payload kinds
|
|
83
|
+
GENERIC = frozenset(
|
|
84
|
+
"concept concepts topic topics idea ideas programming code coding example examples question "
|
|
85
|
+
"questions answer answers help thing things data function functions learning study studying "
|
|
86
|
+
"chat explanation overview basics basic introduction intro general misc other none unknown "
|
|
87
|
+
"test tests problem problems solution solutions method methods approach way ways".split())
|
|
88
|
+
_AT = re.compile(r"^### (\d{4}-\d{2}-\d{2} \d{2}:\d{2})\s*$", re.M)
|
|
89
|
+
_BAD = re.compile(r"[\[\]{}<>|\\/`#*\n]|https?:|www\.", re.I)
|
|
90
|
+
SYSTEM = ("You read the user's side of a study chat with an AI tutor. Name the specific "
|
|
91
|
+
f"concepts the tutor explained: at most {PER_CHAT}, each 1 to 5 words, as a textbook "
|
|
92
|
+
'would title it (for example "Binary search" or "Two pointers"). Never generic words '
|
|
93
|
+
'such as "programming" or "help". If nothing was taught, give an empty list. Reply '
|
|
94
|
+
'with JSON only: {"concepts": ["..."]}')
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Chat:
|
|
99
|
+
id: str
|
|
100
|
+
title: str
|
|
101
|
+
turns: list[str]
|
|
102
|
+
start: datetime | None # UTC, from the turn headings
|
|
103
|
+
end: datetime | None
|
|
104
|
+
day: str
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def text(self) -> str:
|
|
108
|
+
return "\n".join([self.title, *self.turns])
|
|
109
|
+
|
|
110
|
+
def last_day(self) -> str:
|
|
111
|
+
return local_day(self.end) if self.end else self.day
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def chat_of(note) -> Chat | None:
|
|
115
|
+
"""The chat on an ordinary chat page (the user's turns), else None."""
|
|
116
|
+
body = note.body
|
|
117
|
+
if note.kind != "resource" or not topics.page_source(body):
|
|
118
|
+
return None
|
|
119
|
+
turns = [t.strip() for t in chat_import._ME.findall(body) if t.strip()]
|
|
120
|
+
if not turns:
|
|
121
|
+
return None # a coding summary, or no turns
|
|
122
|
+
times = []
|
|
123
|
+
for s in _AT.findall(body):
|
|
124
|
+
try:
|
|
125
|
+
times.append(datetime.strptime(s, "%Y-%m-%d %H:%M").astimezone().astimezone(UTC))
|
|
126
|
+
except ValueError:
|
|
127
|
+
continue
|
|
128
|
+
m = chat_import._DATE.search(body)
|
|
129
|
+
day = m[1] if m else str(note.fields.get("date") or "")[:10]
|
|
130
|
+
if not day and times:
|
|
131
|
+
day = local_day(min(times))
|
|
132
|
+
title = str(note.fields.get("title") or note.id)
|
|
133
|
+
return Chat(note.id, title, turns, min(times, default=None), max(times, default=None), day)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def recorded(chat: Chat, learning: list[dict]) -> set[str]:
|
|
137
|
+
"""The page ids a chat model already logged learning for during `chat` (the module
|
|
138
|
+
docstring's rule): event objects and touch ids."""
|
|
139
|
+
out: set[str] = set()
|
|
140
|
+
for e in learning:
|
|
141
|
+
if chat.start is not None:
|
|
142
|
+
try:
|
|
143
|
+
t = parse_ts(e["ts"])
|
|
144
|
+
except (KeyError, TypeError, ValueError):
|
|
145
|
+
continue
|
|
146
|
+
if not chat.start - BEFORE <= t <= chat.end + AFTER:
|
|
147
|
+
continue
|
|
148
|
+
elif e.get("day") != chat.day:
|
|
149
|
+
continue
|
|
150
|
+
if obj := str(e.get("object") or "").partition(":")[2]:
|
|
151
|
+
out.add(obj)
|
|
152
|
+
p = e.get("payload") if isinstance(e.get("payload"), dict) else {}
|
|
153
|
+
out.update(i for i in p.get("ids") or () if isinstance(i, str))
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _learning(events) -> list[dict]:
|
|
158
|
+
out = []
|
|
159
|
+
for e in live(events):
|
|
160
|
+
if e.get("source") in (SOURCE, "imported"):
|
|
161
|
+
continue
|
|
162
|
+
p = e.get("payload") if isinstance(e.get("payload"), dict) else {}
|
|
163
|
+
if e.get("kind") in LEARNING or (e.get("kind") == "log" and p.get("kind") in LEARNING_LOGS):
|
|
164
|
+
out.append(e)
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def hidden_pattern(catalog: Catalog, hide: set[str]) -> re.Pattern | None:
|
|
169
|
+
"""Whole-word titles and aliases of the hidden concepts (planner.hidden), or None."""
|
|
170
|
+
return _pattern(n for e in catalog.entries.values() if e.kind == "concept"
|
|
171
|
+
and e.id in hide for n in (e.title, *e.aliases))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def skip_reason(note, chat: Chat, ctx, hidden: re.Pattern | None, now: datetime) -> str | None:
|
|
175
|
+
"""Why a pass leaves `chat` alone (the module docstring's rules: "private", "old",
|
|
176
|
+
"hidden"), or None. `ctx`: a chat_import.Ctx; `hidden`: `hidden_pattern`'s."""
|
|
177
|
+
if is_private(note) or ctx.audience(chat.text) != "cloud":
|
|
178
|
+
return "private"
|
|
179
|
+
if chat.last_day() < (now - timedelta(days=RECENT_DAYS)).date().isoformat():
|
|
180
|
+
return "old"
|
|
181
|
+
if hidden is not None and hidden.search(chat.text):
|
|
182
|
+
return "hidden"
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _usable(name: str, least: int = MIN_NAME) -> bool:
|
|
187
|
+
words = name.casefold().split()
|
|
188
|
+
return len(name) >= least and not all(w in STOPWORDS or w in GENERIC for w in words)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _pattern(names) -> re.Pattern | None:
|
|
192
|
+
alts = sorted({r"\s+".join(map(re.escape, n.split())) for n in names if _usable(n)},
|
|
193
|
+
key=len, reverse=True)
|
|
194
|
+
return re.compile(r"(?<!\w)(?:" + "|".join(alts) + r")(?!\w)", re.I) if alts else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def clean_name(raw, text: str | None = None) -> str | None:
|
|
198
|
+
"""A model's concept name, tidied, or None when it is junk: too short or long, generic,
|
|
199
|
+
markup or a link, a secret, or none of its longer words occurs in the chat `text`. With no
|
|
200
|
+
`text` (a chat model named it in a tool call) there is no chat check and 2 letters do."""
|
|
201
|
+
if not isinstance(raw, str):
|
|
202
|
+
return None
|
|
203
|
+
name = " ".join(raw.split()).strip(" .,;:-'\"")
|
|
204
|
+
if not name or len(name) > NAME_CHARS or len(name.split()) > NAME_WORDS or _BAD.search(raw) \
|
|
205
|
+
or not re.search(r"[^\W\d_]", name) or secret_pattern(name) \
|
|
206
|
+
or not _usable(name, 2 if text is None else MIN_NAME):
|
|
207
|
+
return None
|
|
208
|
+
if text is None:
|
|
209
|
+
return name
|
|
210
|
+
low = text.casefold()
|
|
211
|
+
words = [w for w in re.findall(r"\w+", name.casefold()) if len(w) >= 4 and w not in GENERIC]
|
|
212
|
+
return name if any(re.search(rf"(?<!\w){re.escape(w)}", low) for w in words) else None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def ask_model(runner, chat: Chat) -> list[str]:
|
|
216
|
+
"""At most PER_CHAT clean concept names from the runner; [] on any malformed reply."""
|
|
217
|
+
raw = runner.chat(SYSTEM, chat.text[:MODEL_CHARS], max_tokens=200)
|
|
218
|
+
obj = localllm._first_json(raw) if isinstance(raw, str) else None
|
|
219
|
+
items = obj.get("concepts") if isinstance(obj, dict) else None
|
|
220
|
+
if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
|
|
221
|
+
return []
|
|
222
|
+
out: list[str] = []
|
|
223
|
+
for x in items:
|
|
224
|
+
n = clean_name(x, chat.text)
|
|
225
|
+
if n and n.casefold() not in {o.casefold() for o in out}:
|
|
226
|
+
out.append(n)
|
|
227
|
+
return out[:PER_CHAT]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# ---- the pass ---------------------------------------------------------------------------------
|
|
231
|
+
|
|
232
|
+
def _load(vault: Vault, state: str = STATE) -> dict:
|
|
233
|
+
try:
|
|
234
|
+
d = json.loads((vault.root / state).read_text(encoding="utf-8"))
|
|
235
|
+
except (OSError, ValueError):
|
|
236
|
+
return {}
|
|
237
|
+
return d if isinstance(d, dict) else {}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _todo(vault: Vault, ledger: dict, model: bool) -> list:
|
|
241
|
+
"""(path, sig) of resource pages new or changed since the ledger, plus (with a model)
|
|
242
|
+
chats layer 2 has not seen yet. Stats only."""
|
|
243
|
+
out = []
|
|
244
|
+
for p in vault.note_paths("resource"):
|
|
245
|
+
try:
|
|
246
|
+
st = p.stat()
|
|
247
|
+
except OSError:
|
|
248
|
+
continue
|
|
249
|
+
sig = [st.st_mtime_ns, st.st_size]
|
|
250
|
+
rec = ledger.get(p.stem)
|
|
251
|
+
if not isinstance(rec, dict) or rec.get("sig") != sig or (model and rec.get("l2") is False):
|
|
252
|
+
out.append((p, sig))
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class Linker:
|
|
257
|
+
"""A concept name to an existing concept, or a new one made like keepfold_add and linked to a
|
|
258
|
+
hub (the module docstring's layer-2 rules). Shared by the safety net, keepfold_log taught and
|
|
259
|
+
self_report, and the concepts an assessment or problem names. `embed`: an embedder already
|
|
260
|
+
in memory, or None; the vectors are built on first use."""
|
|
261
|
+
|
|
262
|
+
def __init__(self, vault: Vault, catalog: Catalog, index: Index, hide: set[str], embed=None):
|
|
263
|
+
self.vault, self.catalog, self.index, self.hide, self.embed = \
|
|
264
|
+
vault, catalog, index, hide, embed
|
|
265
|
+
self.tree = topics.tree(index)
|
|
266
|
+
self.hidden = hidden_pattern(catalog, hide)
|
|
267
|
+
self._vecs = None
|
|
268
|
+
|
|
269
|
+
def vectors(self):
|
|
270
|
+
"""(hub centroids, (concept ids, head vectors) or None), or None with no embedder."""
|
|
271
|
+
if self.embed is None:
|
|
272
|
+
return None
|
|
273
|
+
if self._vecs is None:
|
|
274
|
+
stack = topics.head_stack(self.index, self.embed)
|
|
275
|
+
hv = topics.heads(stack)
|
|
276
|
+
ids = [c for c, e in self.catalog.entries.items()
|
|
277
|
+
if e.kind == "concept" and c in hv and c not in self.hide]
|
|
278
|
+
self._vecs = (topics.centroids(self.index, self.tree, stack),
|
|
279
|
+
(ids, [hv[c] for c in ids]) if ids else None)
|
|
280
|
+
return self._vecs
|
|
281
|
+
|
|
282
|
+
def vec(self, text: str):
|
|
283
|
+
from keepfold import semantic
|
|
284
|
+
return semantic._embed(self.embed, [text])[0]
|
|
285
|
+
|
|
286
|
+
def hub(self, text: str) -> str | None:
|
|
287
|
+
"""The hub `topics.attach` picks for `text`, or None (no embedder or no clear fit)."""
|
|
288
|
+
v = self.vectors()
|
|
289
|
+
return topics.attach(self.vec(text), self.tree, v[0]).hub if v is not None else None
|
|
290
|
+
|
|
291
|
+
def resolve(self, name: str) -> tuple[str, str | None]:
|
|
292
|
+
"""("match", id), ("new", None) or ("drop", None: it names a hidden concept)."""
|
|
293
|
+
if self.hidden is not None and self.hidden.search(name):
|
|
294
|
+
return "drop", None
|
|
295
|
+
try:
|
|
296
|
+
cid = self.catalog.resolve(name) # no skip: a hidden hit is dropped, never copied
|
|
297
|
+
return ("drop", None) if cid in self.hide else ("match", cid)
|
|
298
|
+
except VaultError as e:
|
|
299
|
+
if e.code != "unknown_concept":
|
|
300
|
+
raise
|
|
301
|
+
v = self.vectors()
|
|
302
|
+
if v is not None and v[1] is not None:
|
|
303
|
+
import numpy as np
|
|
304
|
+
ids, vs = v[1]
|
|
305
|
+
cos = np.asarray(vs) @ self.vec(name)
|
|
306
|
+
k = int(np.argmax(cos))
|
|
307
|
+
if float(cos[k]) >= MATCH_COS:
|
|
308
|
+
return "match", ids[k]
|
|
309
|
+
return "new", None
|
|
310
|
+
|
|
311
|
+
def area(self, matched: list[str], hub: str | None = None) -> str:
|
|
312
|
+
"""The area most `matched` concepts share, else the one most concepts filed under `hub`
|
|
313
|
+
share, else DOMAIN > AREA (made once)."""
|
|
314
|
+
def common(ids):
|
|
315
|
+
areas = Counter(e.parent for c in ids if (e := self.catalog.entries.get(c))
|
|
316
|
+
and e.kind == "concept" and c not in self.hide
|
|
317
|
+
and e.parent and e.parent not in self.hide)
|
|
318
|
+
return areas.most_common(1)[0][0] if areas else None
|
|
319
|
+
|
|
320
|
+
aid = common(matched) or (hub and common(sorted(
|
|
321
|
+
topics.members(self.index, self.tree).get(hub, ()))))
|
|
322
|
+
if aid:
|
|
323
|
+
return aid
|
|
324
|
+
cat = self.catalog
|
|
325
|
+
did = slugify(DOMAIN)
|
|
326
|
+
if getattr(cat.entries.get(did), "kind", None) != "domain":
|
|
327
|
+
did = cat.add("domain", DOMAIN, force=True)
|
|
328
|
+
aid = f"{did}.{slugify(AREA)}"
|
|
329
|
+
if aid not in cat.entries:
|
|
330
|
+
aid = cat.add("area", AREA, did, force=True)
|
|
331
|
+
return aid
|
|
332
|
+
|
|
333
|
+
def create(self, name: str, matched: list[str], text: str = "") -> tuple[str | None, bool]:
|
|
334
|
+
"""(concept id, created) for a name no concept matched; (None, False) when refused.
|
|
335
|
+
`text`: more words to place it by (a summary), embedded with the name."""
|
|
336
|
+
hub = self.hub(f"{name}\n{text}".strip())
|
|
337
|
+
try:
|
|
338
|
+
cid = self.catalog.add("concept", name, self.area(matched, hub))
|
|
339
|
+
except VaultError as e:
|
|
340
|
+
dups = e.did_you_mean or []
|
|
341
|
+
if e.code == "duplicate_suggested": # keepfold_add's "did you mean": the first one
|
|
342
|
+
ok = dups and not any(d in self.hide for d in dups) # never near a hidden one
|
|
343
|
+
return (dups[0], False) if ok else (None, False)
|
|
344
|
+
if e.code in ("invalid_argument", "invalid_id", "secret_detected"):
|
|
345
|
+
return None, False
|
|
346
|
+
raise
|
|
347
|
+
if hub:
|
|
348
|
+
self.vault._edit_fields("concept", cid, {"related": [f"[[{hub}]]"]})
|
|
349
|
+
self.index.refresh()
|
|
350
|
+
return cid, True
|
|
351
|
+
|
|
352
|
+
def link(self, name: str, matched: list[str], text: str = "") -> tuple[str | None, bool]:
|
|
353
|
+
"""(concept id, created), or (None, False) for a name refused or hidden."""
|
|
354
|
+
what, cid = self.resolve(name)
|
|
355
|
+
if what == "new":
|
|
356
|
+
return self.create(name, matched, text)
|
|
357
|
+
return cid, False
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class _Pass:
|
|
361
|
+
def __init__(self, vault: Vault, runner, embed, dry_run: bool, now: datetime):
|
|
362
|
+
self.vault, self.runner, self.embed, self.dry, self.now = vault, runner, embed, dry_run, now
|
|
363
|
+
self.evlog = EventLog(vault)
|
|
364
|
+
self.catalog = Catalog.load(vault)
|
|
365
|
+
self.index = Index(vault, self.catalog)
|
|
366
|
+
self.hide = planner.hidden(vault, self.catalog)
|
|
367
|
+
self.link = Linker(vault, self.catalog, self.index, self.hide, embed)
|
|
368
|
+
evs = live(self.evlog.iter_events())
|
|
369
|
+
self.learning = _learning(evs)
|
|
370
|
+
today = local_day(now)
|
|
371
|
+
self.taught_today = sum(1 for e in evs if e.get("kind") == "taught"
|
|
372
|
+
and e.get("source") == SOURCE and e.get("day") == today)
|
|
373
|
+
self.ctx = chat_import.Ctx(vault)
|
|
374
|
+
self.counts: Counter = Counter()
|
|
375
|
+
self.new_ids: list[str] = []
|
|
376
|
+
self.taught_ids: list[str] = []
|
|
377
|
+
self.events = 0
|
|
378
|
+
self._names()
|
|
379
|
+
|
|
380
|
+
def _names(self) -> None:
|
|
381
|
+
cat, notes = self.catalog.entries, self.index._notes
|
|
382
|
+
self.by_name: dict[str, str] = {} # casefolded name -> page id
|
|
383
|
+
for e in cat.values():
|
|
384
|
+
if e.kind == "concept" and e.id not in self.hide and e.id in notes:
|
|
385
|
+
for n in [e.title, *e.aliases]:
|
|
386
|
+
self.by_name.setdefault(" ".join(n.casefold().split()), e.id)
|
|
387
|
+
for h, title in self.link.tree.title.items():
|
|
388
|
+
if h == topics.ROOT or h not in notes:
|
|
389
|
+
continue
|
|
390
|
+
al = notes[h]["fields"].get("aliases")
|
|
391
|
+
for n in [title, *(al if isinstance(al, list) else [al] if al else [])]:
|
|
392
|
+
self.by_name.setdefault(" ".join(str(n).casefold().split()), h)
|
|
393
|
+
self.public = _pattern(self.by_name)
|
|
394
|
+
|
|
395
|
+
# ---- one chat ----
|
|
396
|
+
|
|
397
|
+
def skip(self, note, chat: Chat) -> str | None:
|
|
398
|
+
return skip_reason(note, chat, self.ctx, self.link.hidden, self.now)
|
|
399
|
+
|
|
400
|
+
def layer1(self, chat: Chat) -> list[str]:
|
|
401
|
+
ids = list(dict.fromkeys(self.by_name[" ".join(m[0].casefold().split())]
|
|
402
|
+
for m in (self.public.finditer(chat.text) if self.public else ())))
|
|
403
|
+
if (hub := self.link.hub(chat.text[:EMBED_CHARS])) and hub not in ids:
|
|
404
|
+
ids.append(hub)
|
|
405
|
+
return ids
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _append(self, kind: str, fields: dict, key: str) -> None:
|
|
409
|
+
if not self.dry:
|
|
410
|
+
self.evlog.append(session="import", kind=kind, source=SOURCE, fields=fields, key=key,
|
|
411
|
+
now=self.now)
|
|
412
|
+
self.events += 1
|
|
413
|
+
|
|
414
|
+
def touch(self, chat: Chat, h: str, ids: list[str], rec: dict) -> None:
|
|
415
|
+
new = [i for i in ids if i not in rec["touched"]][:TOUCHES]
|
|
416
|
+
if not new:
|
|
417
|
+
return
|
|
418
|
+
self._append("log", {"payload": {"kind": "touch", "ids": new, "auto": SOURCE,
|
|
419
|
+
"chat": chat.id}}, f"safety-net:{chat.id}:{h}:touch")
|
|
420
|
+
rec["touched"] += new
|
|
421
|
+
self.counts["touches"] += len(new)
|
|
422
|
+
|
|
423
|
+
def layer2(self, chat: Chat, matched: list[str], rec: dict, done: set[str]) -> None:
|
|
424
|
+
if self.taught_today >= TAUGHT_PER_DAY:
|
|
425
|
+
return # the day's cap: no model call, no new concept
|
|
426
|
+
for name in ask_model(self.runner, chat):
|
|
427
|
+
if self.taught_today >= TAUGHT_PER_DAY:
|
|
428
|
+
break
|
|
429
|
+
what, cid = self.link.resolve(name)
|
|
430
|
+
if what == "drop":
|
|
431
|
+
continue
|
|
432
|
+
made = False
|
|
433
|
+
if what == "new":
|
|
434
|
+
if self.dry:
|
|
435
|
+
self.counts["new"] += 1
|
|
436
|
+
self.new_ids.append(page_slug(name))
|
|
437
|
+
continue
|
|
438
|
+
cid, made = self.link.create(name, matched)
|
|
439
|
+
if cid is None:
|
|
440
|
+
continue
|
|
441
|
+
if made:
|
|
442
|
+
self.counts["new"] += 1
|
|
443
|
+
self.new_ids.append(cid)
|
|
444
|
+
elif cid in rec["taught"] or cid in done: # the chat model logged it already
|
|
445
|
+
continue
|
|
446
|
+
matched.append(cid)
|
|
447
|
+
self._append("taught", {"object": f"concept:{cid}", "payload": {
|
|
448
|
+
"kind": "taught", "auto": SOURCE, "chat": chat.id}},
|
|
449
|
+
f"safety-net:{chat.id}:taught:{cid}")
|
|
450
|
+
rec["taught"].append(cid)
|
|
451
|
+
self.counts["taught"] += 1
|
|
452
|
+
self.taught_today += 1
|
|
453
|
+
self.taught_ids.append(cid)
|
|
454
|
+
|
|
455
|
+
def one(self, note, chat: Chat, h: str, rec: dict) -> dict:
|
|
456
|
+
if why := self.skip(note, chat):
|
|
457
|
+
self.counts[f"skipped_{why}"] += 1
|
|
458
|
+
return {**rec, "what": why, "l2": None}
|
|
459
|
+
rec = {"touched": [], "taught": [], **rec, "what": "done"}
|
|
460
|
+
self.counts["chats"] += 1
|
|
461
|
+
done = recorded(chat, self.learning)
|
|
462
|
+
ids = self.layer1(chat)
|
|
463
|
+
self.touch(chat, h, [i for i in ids if i not in done], rec)
|
|
464
|
+
if self.runner is not None:
|
|
465
|
+
self.layer2(chat, [i for i in dict.fromkeys([*ids, *sorted(done)])
|
|
466
|
+
if i in self.catalog.entries], rec, done)
|
|
467
|
+
rec["l2"] = self.runner is not None
|
|
468
|
+
return rec
|
|
469
|
+
|
|
470
|
+
def line(self) -> str:
|
|
471
|
+
n = self.counts
|
|
472
|
+
s = (f"Safety net: from {n['chats']} chat{'s' * (n['chats'] != 1)}, {n['new']} new "
|
|
473
|
+
f"concept{'s' * (n['new'] != 1)}, {n['taught']} taught, {n['touches']} "
|
|
474
|
+
f"touch{'es' * (n['touches'] != 1)}")
|
|
475
|
+
if self.new_ids:
|
|
476
|
+
s += " (new: " + ", ".join(f"[[{i}]]" for i in self.new_ids) + ")"
|
|
477
|
+
rest = [i for i in self.taught_ids if i not in self.new_ids]
|
|
478
|
+
if rest:
|
|
479
|
+
s += " (taught: " + ", ".join(f"[[{i}]]" for i in rest) + ")"
|
|
480
|
+
return s
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def run(vault: Vault, runner=None, embed=None, *, dry_run: bool = False,
|
|
484
|
+
now: datetime | None = None) -> dict:
|
|
485
|
+
"""One pass. `runner`: a local runner whose model is already loaded, or None (layer 2 is
|
|
486
|
+
skipped); `embed`: an embedder already in memory, or None. Returns counts (chats, touches,
|
|
487
|
+
taught, new, skipped_<why>), `new_ids`, `taught_ids` and `line` when anything was recorded.
|
|
488
|
+
VaultError("busy") while another pass runs."""
|
|
489
|
+
now = now or datetime.now(UTC)
|
|
490
|
+
ledger = _load(vault)
|
|
491
|
+
todo = _todo(vault, ledger, runner is not None)
|
|
492
|
+
if not todo:
|
|
493
|
+
return {}
|
|
494
|
+
lock = nullcontext() if dry_run else vault.job_lock(LOCK, 0, BUSY)
|
|
495
|
+
with lock:
|
|
496
|
+
p, skipped, work = None, Counter(), []
|
|
497
|
+
for path, sig in todo:
|
|
498
|
+
try:
|
|
499
|
+
note = vault.read("resource", path.stem)
|
|
500
|
+
except VaultError:
|
|
501
|
+
continue
|
|
502
|
+
h = chat_import._hash(note.body)
|
|
503
|
+
rec = ledger.get(path.stem) if isinstance(ledger.get(path.stem), dict) else {}
|
|
504
|
+
if rec.get("hash") == h and not (runner is not None and rec.get("l2") is False):
|
|
505
|
+
ledger[path.stem] = {**rec, "sig": sig} # only frontmatter or Topics: changed
|
|
506
|
+
elif (chat := chat_of(note)) is None: # most resources: no index or catalog needed
|
|
507
|
+
skipped["skipped_not_chat"] += 1
|
|
508
|
+
ledger[path.stem] = {"what": "not_chat", "sig": sig, "hash": h}
|
|
509
|
+
else:
|
|
510
|
+
work.append((note, chat, sig, h, rec if rec.get("hash") == h else
|
|
511
|
+
{k: rec[k] for k in ("touched", "taught") if k in rec}))
|
|
512
|
+
work.sort(key=lambda x: (x[1].last_day(), x[0].id), reverse=True) # newest first
|
|
513
|
+
try:
|
|
514
|
+
for note, chat, sig, h, rec in work:
|
|
515
|
+
p = p or _Pass(vault, runner, embed, dry_run, now)
|
|
516
|
+
if p.skip(note, chat) is None and (
|
|
517
|
+
p.counts["chats"] >= MAX_CHATS or p.events + 1 + PER_CHAT > MAX_EVENTS):
|
|
518
|
+
p.counts["left"] += 1 # next pass
|
|
519
|
+
continue
|
|
520
|
+
ledger[note.id] = {**p.one(note, chat, h, rec), "sig": sig, "hash": h}
|
|
521
|
+
finally:
|
|
522
|
+
if not dry_run:
|
|
523
|
+
vault.write_text(vault.root / STATE, json.dumps(ledger, sort_keys=True))
|
|
524
|
+
out: dict = dict(skipped + (p.counts if p else Counter()))
|
|
525
|
+
if p is not None and p.events:
|
|
526
|
+
out.update(new_ids=p.new_ids, taught_ids=p.taught_ids, line=p.line())
|
|
527
|
+
if not dry_run:
|
|
528
|
+
at = now.astimezone()
|
|
529
|
+
vault.append_journal(local_day(now), at.strftime("%H:%M"), p.line())
|
|
530
|
+
return out
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def pending(vault: Vault) -> bool:
|
|
534
|
+
"""Is there a page for a pass to look at (stats only)? The app asks before it probes
|
|
535
|
+
for a loaded model."""
|
|
536
|
+
return bool(_todo(vault, _load(vault), True))
|
|
537
|
+
|
|
538
|
+
def undo(vault: Vault, chat: str | None = None, now: datetime | None = None) -> int:
|
|
539
|
+
"""Void every live safety-net event (only `chat`'s with a page id); returns how many. The
|
|
540
|
+
ledger keeps those chats done, so the next pass does not record them again."""
|
|
541
|
+
evlog = EventLog(vault)
|
|
542
|
+
n = 0
|
|
543
|
+
for e in live(evlog.iter_events()):
|
|
544
|
+
p = e.get("payload")
|
|
545
|
+
if e.get("source") == SOURCE and isinstance(p, dict) and p.get("auto") == SOURCE \
|
|
546
|
+
and (chat is None or p.get("chat") == chat):
|
|
547
|
+
void_event(evlog, session="cli", event_id=e["id"], reason="safety net undo",
|
|
548
|
+
source="external", now=now)
|
|
549
|
+
n += 1
|
|
550
|
+
return n
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def background_tools():
|
|
554
|
+
"""(runner, embed) for the app: the runner only when the PC is idle and the model is
|
|
555
|
+
already loaded (browse.titles.may_run), the embedder only when already in memory (M1: not
|
|
556
|
+
after its idle drop, which the next foreground call undoes), and then one whose use keeps
|
|
557
|
+
it no longer than a person's last use would (M3: `semantic.loaded_embedder`)."""
|
|
558
|
+
from keepfold import semantic
|
|
559
|
+
from keepfold.browse import titles
|
|
560
|
+
return titles.may_run()[0], semantic.loaded_embedder()
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def cli_tools():
|
|
564
|
+
"""(runner, embed) for `keepfold safety-net`: an already-loaded model (no idle wait: the
|
|
565
|
+
owner ran it) and the downloaded embedder, if any; nothing is downloaded or loaded."""
|
|
566
|
+
from keepfold import semantic
|
|
567
|
+
try:
|
|
568
|
+
runner = localllm.find_loaded()
|
|
569
|
+
except ValueError:
|
|
570
|
+
runner = None
|
|
571
|
+
return runner, semantic.load_embedder()
|
keepfold/sample.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""The packaged sample vault (a made-up learner, Sam): `seed` copies it into a vault where
|
|
2
|
+
files are missing and logs a few seed events; `remove` deletes only `sample: true` pages,
|
|
3
|
+
drops their catalog entries and voids the seed events (history is never deleted)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import UTC, datetime, timedelta
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from keepfold.catalog import Catalog
|
|
11
|
+
from keepfold.catalog import sync as catalog_sync
|
|
12
|
+
from keepfold.events import EventLog, live, void_event
|
|
13
|
+
from keepfold.vault import Vault, VaultError
|
|
14
|
+
|
|
15
|
+
SAMPLE_DIR = Path(__file__).parent / "sample_vault"
|
|
16
|
+
KEY = "sample:"
|
|
17
|
+
# (key, kind, days ago, fields): server-stamped fields come from EventLog.append
|
|
18
|
+
SEED = [
|
|
19
|
+
("sample:1", "grade", 9, {"object": "concept:loops", "verdict": "wrong", "hints": 1,
|
|
20
|
+
"mistakes": ["programming.off-by-one-loop"]}),
|
|
21
|
+
("sample:2", "grade", 6, {"object": "concept:loops", "verdict": "correct", "hints": 0}),
|
|
22
|
+
("sample:3", "grade", 3, {"object": "concept:loops", "verdict": "correct", "hints": 0}),
|
|
23
|
+
("sample:4", "grade", 5, {"object": "concept:functions", "verdict": "correct",
|
|
24
|
+
"hints": 0}),
|
|
25
|
+
("sample:5", "grade", 1, {"object": "concept:recursion", "verdict": "partial",
|
|
26
|
+
"hints": 1}),
|
|
27
|
+
("sample:6", "taught", 2, {"object": "concept:big-o-notation"}),
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def files() -> list[str]:
|
|
32
|
+
"""Vault-relative paths of the sample pages."""
|
|
33
|
+
return sorted(p.relative_to(SAMPLE_DIR).as_posix() for p in SAMPLE_DIR.rglob("*.md"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def seed(vault: Vault, now: datetime | None = None) -> tuple[list[str], list[str]]:
|
|
37
|
+
"""Copy missing sample pages, sync the catalog, log the seed events once (keyed)."""
|
|
38
|
+
now = now or datetime.now(UTC)
|
|
39
|
+
did, skipped = [], []
|
|
40
|
+
for rel in files():
|
|
41
|
+
dest = vault.root / rel
|
|
42
|
+
if dest.exists():
|
|
43
|
+
skipped.append(rel)
|
|
44
|
+
else:
|
|
45
|
+
vault.write_text(dest, (SAMPLE_DIR / rel).read_bytes().decode("utf-8"))
|
|
46
|
+
did.append(rel)
|
|
47
|
+
catalog_sync(vault)
|
|
48
|
+
log = EventLog(vault)
|
|
49
|
+
new = [s for s in SEED if not log.has_key(s[0])]
|
|
50
|
+
for key, kind, days, fields in new:
|
|
51
|
+
log.append(session="cli", kind=kind, source="external", key=key, fields=fields,
|
|
52
|
+
now=now - timedelta(days=days))
|
|
53
|
+
(did if new else skipped).append(f"{len(SEED)} events")
|
|
54
|
+
return did, skipped
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_sample(vault: Vault, path: Path) -> bool:
|
|
58
|
+
try:
|
|
59
|
+
return vault.read_path(path).fields.get("sample") is True
|
|
60
|
+
except VaultError:
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def remove(vault: Vault) -> tuple[list[str], int]:
|
|
65
|
+
"""Delete `sample: true` pages and their catalog entries; void the live seed events.
|
|
66
|
+
Returns (removed paths, events voided)."""
|
|
67
|
+
root = vault.root
|
|
68
|
+
paths = [p for p in sorted(root.rglob("*.md"))
|
|
69
|
+
if not p.relative_to(root).parts[0].startswith(".") and _is_sample(vault, p)]
|
|
70
|
+
gone = set()
|
|
71
|
+
for p in paths:
|
|
72
|
+
vault.remove(p)
|
|
73
|
+
if p.parent.name in ("concepts", "areas", "domains"):
|
|
74
|
+
gone.add(p.stem)
|
|
75
|
+
_drop_entries(vault, gone)
|
|
76
|
+
log = EventLog(vault)
|
|
77
|
+
n = 0
|
|
78
|
+
for e in live(log.iter_events()):
|
|
79
|
+
if str(e.get("key", "")).startswith(KEY):
|
|
80
|
+
void_event(log, session="cli", event_id=e["id"], reason="sample removed",
|
|
81
|
+
source="external")
|
|
82
|
+
n += 1
|
|
83
|
+
return [p.relative_to(root).as_posix() for p in paths], n
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _drop_entries(vault: Vault, ids: set[str]) -> None:
|
|
87
|
+
"""Take removed pages out of catalog.yaml (sync would otherwise re-create them). An area
|
|
88
|
+
or domain that still holds other entries stays."""
|
|
89
|
+
with vault.lock():
|
|
90
|
+
cat = Catalog.load(vault)
|
|
91
|
+
cat._reload()
|
|
92
|
+
changed = False
|
|
93
|
+
for kind in ("concept", "area", "domain"): # children first
|
|
94
|
+
for id in sorted(ids):
|
|
95
|
+
e = cat.entries.get(id)
|
|
96
|
+
if e is None or e.kind != kind or cat.children(id):
|
|
97
|
+
continue
|
|
98
|
+
seq, node = cat._node(id)
|
|
99
|
+
seq.remove(node)
|
|
100
|
+
cat._index()
|
|
101
|
+
changed = True
|
|
102
|
+
if changed:
|
|
103
|
+
cat._save()
|