memory-cli 0.1.0__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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""Search over the typed notes: filters, BM25F ranking, links, mentions and the search-eval table (A5, ADR 0028). Pure means no subprocess, no `os.environ` and no file writes; it only reads, and prints a skip warning on stderr for a note it cannot read. The `mem` commands print what it returns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import collections
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import TYPE_CHECKING, TypedDict, Unpack
|
|
13
|
+
|
|
14
|
+
from memory_cli.memories import records
|
|
15
|
+
from memory_cli.notes import index as index_files
|
|
16
|
+
from memory_cli.notes import links as link_rules
|
|
17
|
+
from memory_cli.notes import note as note_files
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Iterable
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_KEY_VALUE_CELLS = 2 # a two-cell table row: name and value
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_MIN_TITLE_WORDS = 4 # a title shorter than this is too generic to match as a phrase
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
_FIND_ONLY_TYPE = {"kind": "literature", "status": "research", "confidence": "knowledge"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_FIND_TYPES = {"level": ("literature", "knowledge")}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _unknown_topic_message(topic: str, known: dict) -> str:
|
|
36
|
+
"""Say what to try instead: ids sharing a word with the guess, and free-text search."""
|
|
37
|
+
words = set(topic.lower().split("-"))
|
|
38
|
+
close = sorted(t for t in known if words & set(t.split("-")) or topic.lower() in t)
|
|
39
|
+
hint = f"close ids: {', '.join(close)}; " if close else ""
|
|
40
|
+
return f'unknown topic {topic}: {hint}for free text use: mem search "{topic.replace("-", " ")}" (ids: topics.yaml)'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NoteFilters(TypedDict, total=False):
|
|
44
|
+
"""The keyword filters of `_matching_notes`, for the functions that pass them on."""
|
|
45
|
+
|
|
46
|
+
type: str | None
|
|
47
|
+
topic: str | None
|
|
48
|
+
kind: str | None
|
|
49
|
+
status: str | None
|
|
50
|
+
confidence: str | None
|
|
51
|
+
level: str | None
|
|
52
|
+
superseded: bool
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _search_types(wanted: dict[str, str | None], type_filter: str | None) -> set[str]:
|
|
56
|
+
"""The note types left after the type filter and the type each other filter implies."""
|
|
57
|
+
types: set[str] = {type_filter} if type_filter else set(index_files.INDEX_FOLDERS)
|
|
58
|
+
for key, value in wanted.items():
|
|
59
|
+
if value is not None:
|
|
60
|
+
types &= set(_FIND_TYPES[key]) if key in _FIND_TYPES else {_FIND_ONLY_TYPE[key]}
|
|
61
|
+
return types
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _search_in_scope(meta: dict, scope: set[str] | None) -> bool:
|
|
65
|
+
"""Whether a note lists a topic of `scope`; every note is in scope when there is none."""
|
|
66
|
+
if scope is None:
|
|
67
|
+
return True
|
|
68
|
+
listed = meta.get("topics")
|
|
69
|
+
return isinstance(listed, list) and bool(
|
|
70
|
+
scope.intersection(t for t in listed if isinstance(t, str))
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _search_matches(
|
|
75
|
+
note: note_files.Note,
|
|
76
|
+
types: set[str],
|
|
77
|
+
wanted: dict[str, str | None],
|
|
78
|
+
scope: set[str] | None,
|
|
79
|
+
superseded: bool,
|
|
80
|
+
) -> bool:
|
|
81
|
+
"""Whether a parsed note passes the type, superseded, field and topic filters."""
|
|
82
|
+
meta = note.meta
|
|
83
|
+
if note.type not in types:
|
|
84
|
+
return False
|
|
85
|
+
if not superseded and meta.get("superseded_by") is not None:
|
|
86
|
+
return False
|
|
87
|
+
if any(v is not None and meta.get(k) != v for k, v in wanted.items()):
|
|
88
|
+
return False
|
|
89
|
+
return _search_in_scope(meta, scope)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _matching_notes(root: Path, **filters: Unpack[NoteFilters]) -> list[note_files.Note]:
|
|
93
|
+
"""Parsable typed notes matching every filter; unparsable ones are skipped with a warning.
|
|
94
|
+
|
|
95
|
+
A note with `superseded_by` is left out unless `superseded`."""
|
|
96
|
+
wanted = {
|
|
97
|
+
"kind": filters.get("kind"),
|
|
98
|
+
"status": filters.get("status"),
|
|
99
|
+
"confidence": filters.get("confidence"),
|
|
100
|
+
"level": filters.get("level"),
|
|
101
|
+
}
|
|
102
|
+
types = _search_types(wanted, filters.get("type"))
|
|
103
|
+
topic = filters.get("topic")
|
|
104
|
+
known = note_files.load_topics(root)
|
|
105
|
+
if topic and topic not in known:
|
|
106
|
+
raise note_files.FrontmatterError(_unknown_topic_message(topic, known))
|
|
107
|
+
scope = note_files.descendants(known, topic) if topic else None
|
|
108
|
+
superseded = filters.get("superseded") or False
|
|
109
|
+
result = []
|
|
110
|
+
for note in note_files.discover_notes(root):
|
|
111
|
+
if note.error is not None or not isinstance(note.meta, dict):
|
|
112
|
+
print(
|
|
113
|
+
f"mem: skipping {note.rel}: {note.error or 'frontmatter is not a mapping'}",
|
|
114
|
+
file=sys.stderr,
|
|
115
|
+
)
|
|
116
|
+
continue
|
|
117
|
+
if _search_matches(note, types, wanted, scope, superseded):
|
|
118
|
+
result.append(note)
|
|
119
|
+
return result
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _title(note: note_files.Note) -> str:
|
|
123
|
+
return str(note.meta.get("claim" if note.type == "knowledge" else "title", ""))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def find(root: Path, **filters: Unpack[NoteFilters]) -> list[tuple[str, str]]:
|
|
127
|
+
"""(rel, title) of notes matching every filter; claim is the title of knowledge notes."""
|
|
128
|
+
return sorted((n.rel, _title(n)) for n in _matching_notes(root, **filters))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# BM25F (Robertson, Zaragoza and Taylor 2004): each field is length-normalized on its own, the weighted
|
|
132
|
+
# term frequencies are summed, and saturation is applied once. Parameters were tuned on docs/search-eval.md
|
|
133
|
+
# and held on both held-out halves of it (ADR 0007); retune only the same way.
|
|
134
|
+
BM25_K1 = 2.0
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
FIELD_WEIGHTS = {"title": 8.0, "body": 1.0}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
FIELD_B = {"title": 0.3, "body": 0.75}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _fields(note: note_files.Note) -> dict[str, str]:
|
|
144
|
+
"""Searchable text per field: the title (`claim` for knowledge notes), and the body with topics and authors."""
|
|
145
|
+
meta = note.meta
|
|
146
|
+
extra = [
|
|
147
|
+
" ".join(str(v) for v in meta[f])
|
|
148
|
+
for f in ("topics", "authors")
|
|
149
|
+
if isinstance(meta.get(f), list)
|
|
150
|
+
]
|
|
151
|
+
return {"title": _title(note), "body": "\n".join([*extra, note.body])}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class Corpus:
|
|
156
|
+
"""Notes with per-field term counts and lengths, so many queries can be ranked without re-reading notes."""
|
|
157
|
+
|
|
158
|
+
notes: list[note_files.Note]
|
|
159
|
+
counts: list[dict[str, collections.Counter]]
|
|
160
|
+
lengths: list[dict[str, int]]
|
|
161
|
+
average: dict[str, float]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def build_corpus(root: Path, **filters: Unpack[NoteFilters]) -> Corpus:
|
|
165
|
+
"""Read and tokenize the notes matching `filters` once."""
|
|
166
|
+
notes = _matching_notes(root, **filters)
|
|
167
|
+
counts = [
|
|
168
|
+
{f: collections.Counter(records.tokenize(text)) for f, text in _fields(n).items()}
|
|
169
|
+
for n in notes
|
|
170
|
+
]
|
|
171
|
+
lengths = [{f: sum(c.values()) for f, c in fields.items()} for fields in counts]
|
|
172
|
+
total = len(notes)
|
|
173
|
+
average = {f: sum(l[f] for l in lengths) / total if total else 0.0 for f in FIELD_WEIGHTS}
|
|
174
|
+
return Corpus(notes, counts, lengths, average)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def term_idf(corpus: Corpus, terms: Iterable[str]) -> dict[str, float]:
|
|
178
|
+
"""BM25 IDF of each term, where a note counts when the term is in any of its fields."""
|
|
179
|
+
total = len(corpus.notes)
|
|
180
|
+
idf = {}
|
|
181
|
+
for term in terms:
|
|
182
|
+
n = sum(1 for fields in corpus.counts if any(term in c for c in fields.values()))
|
|
183
|
+
idf[term] = math.log(1 + (total - n + 0.5) / (n + 0.5))
|
|
184
|
+
return idf
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def rank(corpus: Corpus, query: str, *, limit: int = 10) -> list[tuple[note_files.Note, float]]:
|
|
188
|
+
"""(note, score) of the best BM25F matches, best first, ties by `note.rel`; notes scoring 0 are omitted."""
|
|
189
|
+
terms = list(dict.fromkeys(records.tokenize(query)))
|
|
190
|
+
idf = term_idf(corpus, terms)
|
|
191
|
+
scored = []
|
|
192
|
+
for note, fields, length in zip(corpus.notes, corpus.counts, corpus.lengths, strict=False):
|
|
193
|
+
score = 0.0
|
|
194
|
+
for term in terms:
|
|
195
|
+
tf = sum(
|
|
196
|
+
FIELD_WEIGHTS[f]
|
|
197
|
+
* fields[f][term]
|
|
198
|
+
/ (1 - FIELD_B[f] + FIELD_B[f] * length[f] / corpus.average[f])
|
|
199
|
+
for f in FIELD_WEIGHTS
|
|
200
|
+
if fields[f].get(term) and corpus.average[f]
|
|
201
|
+
)
|
|
202
|
+
if tf:
|
|
203
|
+
score += idf[term] * tf * (BM25_K1 + 1) / (tf + BM25_K1)
|
|
204
|
+
if score > 0:
|
|
205
|
+
scored.append((note, score))
|
|
206
|
+
scored.sort(key=lambda r: (-r[1], r[0].rel))
|
|
207
|
+
return scored[:limit]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def search(
|
|
211
|
+
root: Path, query: str, *, limit: int = 10, **filters: Unpack[NoteFilters]
|
|
212
|
+
) -> list[tuple[str, float, str]]:
|
|
213
|
+
"""(rel, score, title) of the best BM25F matches, best first; notes scoring 0 are omitted."""
|
|
214
|
+
return [
|
|
215
|
+
(n.rel, score, _title(n))
|
|
216
|
+
for n, score in rank(build_corpus(root, **filters), query, limit=limit)
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
LINK_SEEDS = LINK_EXTRA = 10
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def linked_notes(
|
|
224
|
+
root: Path, corpus: Corpus, ranked: list[tuple[note_files.Note, float]], shown: int
|
|
225
|
+
) -> list[tuple[note_files.Note, float]]:
|
|
226
|
+
"""Up to `LINK_EXTRA` notes of `corpus` linked to or from the first `LINK_SEEDS` printed results of `ranked` (the full
|
|
227
|
+
ranking), not among its first `shown`, as (note, own score; 0 when it does not match the query).
|
|
228
|
+
|
|
229
|
+
Order, as measured (tools/README.md): the scores of the seeds a note is linked with, summed, plus its own
|
|
230
|
+
score, ties by path. Links are those `related` reads between typed notes."""
|
|
231
|
+
in_corpus = {n.rel for n in corpus.notes}
|
|
232
|
+
graph: dict[str, set[str]] = {rel: set() for rel in in_corpus}
|
|
233
|
+
for note in corpus.notes:
|
|
234
|
+
for target in _link_targets(root, note):
|
|
235
|
+
if target in in_corpus and target != note.rel:
|
|
236
|
+
graph[note.rel].add(target)
|
|
237
|
+
graph[target].add(note.rel)
|
|
238
|
+
own = {n.rel: score for n, score in ranked}
|
|
239
|
+
printed = {n.rel for n, _ in ranked[:shown]}
|
|
240
|
+
support: dict[str, float] = {}
|
|
241
|
+
for note, score in ranked[
|
|
242
|
+
: min(shown, LINK_SEEDS)
|
|
243
|
+
]: # seeds are printed results, so "above" holds
|
|
244
|
+
for rel in graph[note.rel] - printed:
|
|
245
|
+
support[rel] = support.get(rel, 0.0) + score
|
|
246
|
+
best = sorted(support, key=lambda rel: (-(support[rel] + own.get(rel, 0.0)), rel))[:LINK_EXTRA]
|
|
247
|
+
by_rel = {n.rel: n for n in corpus.notes}
|
|
248
|
+
return [(by_rel[rel], own.get(rel, 0.0)) for rel in best]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
_EVAL_FILE = "docs/search-eval.md"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
_MD_LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def eval_rows(root: Path) -> list[tuple[int, str, list[str]]] | None:
|
|
258
|
+
"""(line number, query, expected note paths) per row of docs/search-eval.md's query table; None when absent."""
|
|
259
|
+
path = root / _EVAL_FILE
|
|
260
|
+
if not path.is_file():
|
|
261
|
+
return None
|
|
262
|
+
rows = []
|
|
263
|
+
in_table = False # only the table whose header is "| Query | Expected notes |" holds queries
|
|
264
|
+
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
|
265
|
+
if not line.lstrip().startswith("|"):
|
|
266
|
+
in_table = False
|
|
267
|
+
continue
|
|
268
|
+
cells = [c.strip() for c in line.strip().strip("|").split("|")]
|
|
269
|
+
if cells[:1] == ["Query"]:
|
|
270
|
+
in_table = True
|
|
271
|
+
continue
|
|
272
|
+
if (
|
|
273
|
+
not in_table
|
|
274
|
+
or len(cells) != _KEY_VALUE_CELLS
|
|
275
|
+
or not cells[0]
|
|
276
|
+
or set(cells[0]) <= set("-: ")
|
|
277
|
+
):
|
|
278
|
+
continue
|
|
279
|
+
wanted = [
|
|
280
|
+
os.path.normpath(f"docs/{m.split('#')[0]}").replace(os.sep, "/")
|
|
281
|
+
for m in _MD_LINK.findall(cells[1])
|
|
282
|
+
]
|
|
283
|
+
rows.append((number, cells[0].strip("`"), wanted))
|
|
284
|
+
return rows
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
RELATIONS = ("links-to", "linked-from", "similar")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _link_targets(root: Path, note: note_files.Note) -> set[str]:
|
|
291
|
+
"""Hub-relative paths the note links to (a folder link means its README.md), as `orphan_notes` resolves them."""
|
|
292
|
+
targets = set()
|
|
293
|
+
for _, _, file_part in link_rules._relative_links(note.body, refs=True):
|
|
294
|
+
target = os.path.normpath(root / Path(note.rel).parent / file_part)
|
|
295
|
+
if Path(target).is_dir():
|
|
296
|
+
target = os.path.join(target, "README.md")
|
|
297
|
+
targets.add(Path(os.path.relpath(target, root)).as_posix())
|
|
298
|
+
return targets
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def related(
|
|
302
|
+
root: Path, rel: str, *, limit: int = 5, corpus: Corpus | None = None
|
|
303
|
+
) -> dict[str, list[note_files.Note]]:
|
|
304
|
+
"""Notes `rel` links to, notes linking to it (typed notes only, by path) and its `limit` most similar notes.
|
|
305
|
+
|
|
306
|
+
Raises ValueError when `rel` is not a typed note; pass `corpus` (of all notes) to reuse one already built."""
|
|
307
|
+
corpus = corpus or build_corpus(root)
|
|
308
|
+
note = next((n for n in corpus.notes if n.rel == rel), None)
|
|
309
|
+
if note is None:
|
|
310
|
+
raise ValueError(f"not a note: {rel}")
|
|
311
|
+
outgoing = _link_targets(root, note)
|
|
312
|
+
links_to = [n for n in corpus.notes if n.rel in outgoing and n.rel != rel]
|
|
313
|
+
linked_from = [n for n in corpus.notes if n.rel != rel and rel in _link_targets(root, n)]
|
|
314
|
+
seen = {rel, *(n.rel for n in links_to + linked_from)}
|
|
315
|
+
similar = [
|
|
316
|
+
n for n, _ in rank(corpus, _title(note), limit=limit + len(seen)) if n.rel not in seen
|
|
317
|
+
]
|
|
318
|
+
return {
|
|
319
|
+
"links-to": sorted(links_to, key=lambda n: n.rel),
|
|
320
|
+
"linked-from": sorted(linked_from, key=lambda n: n.rel),
|
|
321
|
+
"similar": similar[:limit],
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _mention_pattern(note: note_files.Note) -> re.Pattern[str] | None:
|
|
326
|
+
"""Regex for text that names `note` without linking it: its title as a phrase (4+ words), and for a
|
|
327
|
+
literature note also `Surname ... YEAR` (first author's last word, case-sensitive, within 40 characters)."""
|
|
328
|
+
words = re.findall(r"\w+", _title(note))
|
|
329
|
+
parts = (
|
|
330
|
+
[r"(?i:\b" + r"\W+".join(map(re.escape, words)) + r"\b)"]
|
|
331
|
+
if len(words) >= _MIN_TITLE_WORDS
|
|
332
|
+
else []
|
|
333
|
+
)
|
|
334
|
+
authors = note.meta.get("authors")
|
|
335
|
+
if (
|
|
336
|
+
note.type == "literature"
|
|
337
|
+
and isinstance(authors, list)
|
|
338
|
+
and authors
|
|
339
|
+
and str(authors[0]).split()
|
|
340
|
+
):
|
|
341
|
+
surname = str(authors[0]).split()[-1]
|
|
342
|
+
parts.append(
|
|
343
|
+
rf"\b{re.escape(surname)}\b.{{0,40}}\b{re.escape(str(note.meta.get('year')))}\b"
|
|
344
|
+
)
|
|
345
|
+
return re.compile("|".join(parts), re.DOTALL) if parts else None
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def unlinked_mentions(root: Path, rel: str, corpus: Corpus) -> list[note_files.Note]:
|
|
349
|
+
"""Typed notes whose body names `rel`'s note (see `_mention_pattern`) without linking to it, by path.
|
|
350
|
+
|
|
351
|
+
Markdown links are removed before looking, so the label of a link to another note is not a mention."""
|
|
352
|
+
note = next((n for n in corpus.notes if n.rel == rel), None)
|
|
353
|
+
if note is None:
|
|
354
|
+
raise ValueError(f"not a note: {rel}")
|
|
355
|
+
pattern = _mention_pattern(note)
|
|
356
|
+
if pattern is None:
|
|
357
|
+
return []
|
|
358
|
+
return sorted(
|
|
359
|
+
(
|
|
360
|
+
n
|
|
361
|
+
for n in corpus.notes
|
|
362
|
+
if n.rel != rel
|
|
363
|
+
and pattern.search(link_rules._LINK.sub("", n.body))
|
|
364
|
+
and rel not in _link_targets(root, n)
|
|
365
|
+
),
|
|
366
|
+
key=lambda n: n.rel,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def search_eval(root: Path, *, limit: int = 10) -> tuple[list[str], int, int, float] | None:
|
|
371
|
+
"""(misses, found, expected, reciprocal-rank sum) for docs/search-eval.md; None when it is absent.
|
|
372
|
+
|
|
373
|
+
The reciprocal-rank sum divided by `expected` is MRR@limit: it moves when a note climbs or falls
|
|
374
|
+
inside the top `limit`, which recall alone does not show (used to tune BM25; see ADR 0003)."""
|
|
375
|
+
rows = eval_rows(root)
|
|
376
|
+
if rows is None:
|
|
377
|
+
return None
|
|
378
|
+
corpus = build_corpus(root)
|
|
379
|
+
misses, found, expected, reciprocal = [], 0, 0, 0.0
|
|
380
|
+
for number, query, wanted in rows:
|
|
381
|
+
top = (
|
|
382
|
+
[n.rel for n, _ in rank(corpus, query, limit=limit)] if records.tokenize(query) else []
|
|
383
|
+
)
|
|
384
|
+
for rel in wanted:
|
|
385
|
+
expected += 1
|
|
386
|
+
if rel in top:
|
|
387
|
+
found += 1
|
|
388
|
+
reciprocal += 1 / (top.index(rel) + 1)
|
|
389
|
+
else:
|
|
390
|
+
misses.append(f'{_EVAL_FILE}:{number}: missed {rel} for "{query}"')
|
|
391
|
+
return misses, found, expected, reciprocal
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Find synthesis parts with enough notes on a more specific topic to split."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from memory_cli.notes.note import ancestors
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Iterable, Mapping
|
|
13
|
+
|
|
14
|
+
from memory_cli.notes.note import Note
|
|
15
|
+
from memory_cli.syntheses.document import Synthesis
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
MIN_NOTES = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class SplitCandidate:
|
|
23
|
+
part: str
|
|
24
|
+
topic: str
|
|
25
|
+
notes: tuple[str, ...]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def find_candidates(
|
|
29
|
+
notes: Iterable[Note], syntheses: Iterable[Synthesis], topics: Mapping[str, dict]
|
|
30
|
+
) -> list[SplitCandidate]:
|
|
31
|
+
"""Report strict descendant topics named by five distinct live notes on an existing part."""
|
|
32
|
+
parts = {
|
|
33
|
+
f"{syn.handle}#{section.handle}": syn
|
|
34
|
+
for syn in syntheses
|
|
35
|
+
if syn.error is None
|
|
36
|
+
for section in syn.parts
|
|
37
|
+
}
|
|
38
|
+
known = dict(topics)
|
|
39
|
+
groups: dict[tuple[str, str], set[str]] = defaultdict(set)
|
|
40
|
+
for note in notes:
|
|
41
|
+
part = _attached_part(note, parts)
|
|
42
|
+
if part is None:
|
|
43
|
+
continue
|
|
44
|
+
tags = note.meta["topics"]
|
|
45
|
+
declared = set(parts[part].topics)
|
|
46
|
+
for topic in tags:
|
|
47
|
+
if (
|
|
48
|
+
isinstance(topic, str)
|
|
49
|
+
and topic in topics
|
|
50
|
+
and topic not in declared
|
|
51
|
+
and declared.intersection(ancestors(known, topic))
|
|
52
|
+
):
|
|
53
|
+
groups[part, topic].add(note.rel)
|
|
54
|
+
return [
|
|
55
|
+
SplitCandidate(part, topic, tuple(sorted(paths)))
|
|
56
|
+
for (part, topic), paths in sorted(groups.items())
|
|
57
|
+
if len(paths) >= MIN_NOTES
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _attached_part(note: Note, parts: dict[str, Synthesis]) -> str | None:
|
|
62
|
+
if note.type != "knowledge" or note.error is not None or not isinstance(note.meta, dict):
|
|
63
|
+
return None
|
|
64
|
+
part = note.meta.get("part_of")
|
|
65
|
+
if (
|
|
66
|
+
note.meta.get("superseded_by") is not None
|
|
67
|
+
or not isinstance(part, str)
|
|
68
|
+
or part not in parts
|
|
69
|
+
or not isinstance(note.meta.get("topics"), list)
|
|
70
|
+
):
|
|
71
|
+
return None
|
|
72
|
+
return part
|