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.
Files changed (128) hide show
  1. memory_cli/__init__.py +1 -0
  2. memory_cli/__main__.py +49 -0
  3. memory_cli/capture/__init__.py +7 -0
  4. memory_cli/capture/codex_rollout.py +164 -0
  5. memory_cli/capture/event_lines.py +66 -0
  6. memory_cli/capture/extract.py +458 -0
  7. memory_cli/capture/state.py +183 -0
  8. memory_cli/commands/__init__.py +21 -0
  9. memory_cli/commands/admin.py +363 -0
  10. memory_cli/commands/common.py +609 -0
  11. memory_cli/commands/curate.py +1189 -0
  12. memory_cli/commands/diagnostics.py +126 -0
  13. memory_cli/commands/edit.py +1282 -0
  14. memory_cli/commands/hooks.py +730 -0
  15. memory_cli/commands/import_recovery.py +45 -0
  16. memory_cli/commands/install.py +152 -0
  17. memory_cli/commands/integrate.py +480 -0
  18. memory_cli/commands/memory.py +2152 -0
  19. memory_cli/commands/read.py +1290 -0
  20. memory_cli/commands/sources.py +766 -0
  21. memory_cli/commands/split.py +97 -0
  22. memory_cli/commands/split_plan.py +196 -0
  23. memory_cli/commands/split_transaction.py +230 -0
  24. memory_cli/commands/synthesis.py +1122 -0
  25. memory_cli/core/__init__.py +16 -0
  26. memory_cli/core/auto_state.py +30 -0
  27. memory_cli/core/codex_pass.py +109 -0
  28. memory_cli/core/config.py +87 -0
  29. memory_cli/core/file_journal.py +163 -0
  30. memory_cli/core/headless.py +130 -0
  31. memory_cli/core/jobs.py +130 -0
  32. memory_cli/core/resources.py +57 -0
  33. memory_cli/core/runner.py +398 -0
  34. memory_cli/core/safe_io.py +155 -0
  35. memory_cli/core/store_git.py +407 -0
  36. memory_cli/core/yaml_load.py +14 -0
  37. memory_cli/corroborate/__init__.py +11 -0
  38. memory_cli/corroborate/cli.py +267 -0
  39. memory_cli/corroborate/decide.py +893 -0
  40. memory_cli/corroborate/digest.py +425 -0
  41. memory_cli/corroborate/fill.py +744 -0
  42. memory_cli/corroborate/job.py +15 -0
  43. memory_cli/corroborate/reword.py +446 -0
  44. memory_cli/corroborate/run.py +1142 -0
  45. memory_cli/corroborate/state.py +300 -0
  46. memory_cli/digest/__init__.py +4 -0
  47. memory_cli/digest/lessons.py +483 -0
  48. memory_cli/entry/__init__.py +12 -0
  49. memory_cli/entry/auto.py +660 -0
  50. memory_cli/entry/capture.py +1403 -0
  51. memory_cli/entry/corroborate.py +214 -0
  52. memory_cli/entry/integrate.py +684 -0
  53. memory_cli/entry/integrate_self_check.py +203 -0
  54. memory_cli/entry/research.py +9 -0
  55. memory_cli/entry/settle.py +614 -0
  56. memory_cli/entry/split_auto.py +460 -0
  57. memory_cli/entry/synthesize.py +22 -0
  58. memory_cli/integrate/__init__.py +9 -0
  59. memory_cli/integrate/answers.py +42 -0
  60. memory_cli/integrate/briefs/check-brief.md +16 -0
  61. memory_cli/integrate/briefs/place-brief.md +26 -0
  62. memory_cli/integrate/log.py +43 -0
  63. memory_cli/integrate/plan.py +125 -0
  64. memory_cli/integrate/rows.py +99 -0
  65. memory_cli/integrate/state.py +158 -0
  66. memory_cli/integrate/undo.py +143 -0
  67. memory_cli/mem.py +1180 -0
  68. memory_cli/memories/__init__.py +16 -0
  69. memory_cli/memories/fingerprints.py +51 -0
  70. memory_cli/memories/journal.py +93 -0
  71. memory_cli/memories/locations.py +282 -0
  72. memory_cli/memories/matching.py +451 -0
  73. memory_cli/memories/model.py +205 -0
  74. memory_cli/memories/parse.py +237 -0
  75. memory_cli/memories/records.py +266 -0
  76. memory_cli/memories/rules.py +291 -0
  77. memory_cli/memories/sightings.py +314 -0
  78. memory_cli/memories/terms.py +148 -0
  79. memory_cli/memories/write.py +358 -0
  80. memory_cli/notes/__init__.py +13 -0
  81. memory_cli/notes/check.py +806 -0
  82. memory_cli/notes/due.py +260 -0
  83. memory_cli/notes/fields.py +217 -0
  84. memory_cli/notes/index.py +230 -0
  85. memory_cli/notes/links.py +170 -0
  86. memory_cli/notes/note.py +222 -0
  87. memory_cli/notes/search.py +391 -0
  88. memory_cli/notes/split_candidates.py +72 -0
  89. memory_cli/research/__init__.py +5 -0
  90. memory_cli/research/checks.py +1065 -0
  91. memory_cli/research/pipeline.py +952 -0
  92. memory_cli/session/__init__.py +5 -0
  93. memory_cli/session/handoff.py +139 -0
  94. memory_cli/session/notices.py +111 -0
  95. memory_cli/settle/__init__.py +5 -0
  96. memory_cli/settle/state.py +111 -0
  97. memory_cli/settle/verdicts.py +693 -0
  98. memory_cli/split/briefs/checker-brief.md +5 -0
  99. memory_cli/split/briefs/editor-brief.md +20 -0
  100. memory_cli/syntheses/__init__.py +8 -0
  101. memory_cli/syntheses/document.py +400 -0
  102. memory_cli/syntheses/edit.py +581 -0
  103. memory_cli/syntheses/project.py +384 -0
  104. memory_cli/syntheses/split_conservation.py +50 -0
  105. memory_cli/syntheses/units.py +427 -0
  106. memory_cli/synthesize/__init__.py +9 -0
  107. memory_cli/synthesize/backfill.py +431 -0
  108. memory_cli/synthesize/briefs/backfill-brief.md +26 -0
  109. memory_cli/synthesize/briefs/checker-brief.md +13 -0
  110. memory_cli/synthesize/briefs/fixer-brief.md +19 -0
  111. memory_cli/synthesize/briefs/memory-brief.md +30 -0
  112. memory_cli/synthesize/briefs/settle-brief.md +32 -0
  113. memory_cli/synthesize/briefs/verdict-brief.md +50 -0
  114. memory_cli/synthesize/briefs/web-brief.md +33 -0
  115. memory_cli/synthesize/cli.py +311 -0
  116. memory_cli/synthesize/pipeline.py +764 -0
  117. memory_cli/synthesize/references.py +164 -0
  118. memory_cli/synthesize/run.py +150 -0
  119. memory_cli/synthesize/topics.py +528 -0
  120. memory_cli/templates/knowledge.md +23 -0
  121. memory_cli/templates/literature.md +25 -0
  122. memory_cli/templates/research.md +23 -0
  123. memory_cli/templates/synthesis.md +6 -0
  124. memory_cli-0.1.0.dist-info/METADATA +102 -0
  125. memory_cli-0.1.0.dist-info/RECORD +128 -0
  126. memory_cli-0.1.0.dist-info/WHEEL +4 -0
  127. memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
  128. memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1290 @@
1
+ """The `check`, `index`, `find`, `topics`, `show`, `search`, `passages`, `related`, `search-eval`, `stats` and `review` handlers (A5, ADR 0028): the read commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import dataclasses
7
+ import datetime
8
+ import math
9
+ import os
10
+ import re
11
+ import sys
12
+ from dataclasses import dataclass
13
+ from functools import cached_property
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Any, TypedDict, Unpack, cast
16
+
17
+ from memory_cli.commands import common
18
+ from memory_cli.core import resources
19
+ from memory_cli.memories import records
20
+ from memory_cli.notes import check as check_rules
21
+ from memory_cli.notes import due as due_queries
22
+ from memory_cli.notes import index as index_files
23
+ from memory_cli.notes import links as link_rules
24
+ from memory_cli.notes import note as note_files
25
+ from memory_cli.notes import search as note_search
26
+ from memory_cli.syntheses import document
27
+ from memory_cli.syntheses import edit as synthesis_edit
28
+ from memory_cli.syntheses import project as project_syntheses
29
+
30
+ if TYPE_CHECKING:
31
+ import argparse
32
+ from collections.abc import Mapping, Sequence
33
+
34
+
35
+ _SECTION_LEVEL = 2 # the heading level of a `## ` section
36
+
37
+
38
+ _SPARSE_HITS = 3 # fewer hits than this makes a search look for more
39
+
40
+
41
+ RECALL_TRIGGER = 0.8 # below these, revisit the search design (C-6 in docs/requirements.md)
42
+
43
+
44
+ MRR_TRIGGER = 0.6
45
+
46
+
47
+ _HEADING = re.compile(r"^(#{1,4})[ \t]+\S")
48
+
49
+
50
+ def _headings(lines: list[str]) -> list[tuple[int, int, str]]:
51
+ """(0-based index, level, text) of each Markdown heading outside fenced code."""
52
+ return [
53
+ (i, len(h.group(1)), line)
54
+ for i, (line, fenced) in enumerate(zip(lines, link_rules._in_fence(lines), strict=False))
55
+ if not fenced and (h := _HEADING.match(line))
56
+ ]
57
+
58
+
59
+ def _sections(lines: list[str], wanted: list[str]) -> list[str]:
60
+ """Requested `## ` sections in the note's order, then a message per absent one."""
61
+ h2 = [
62
+ (i, line[2:].strip().casefold())
63
+ for i, level, line in _headings(lines)
64
+ if level == _SECTION_LEVEL
65
+ ]
66
+ keys = {w.strip().casefold() for w in wanted}
67
+ out: list[str] = []
68
+ seen: set[str] = set()
69
+ for n, (start, key) in enumerate(h2):
70
+ if key in keys:
71
+ seen.add(key)
72
+ end = h2[n + 1][0] if n + 1 < len(h2) else len(lines)
73
+ out.extend(lines[start:end])
74
+ out.extend(f'(no section "{w}")' for w in wanted if w.strip().casefold() not in seen)
75
+ return out
76
+
77
+
78
+ _KEY_FACTS = {
79
+ "knowledge": ("confidence", "updated", "level"),
80
+ "literature": ("year", "kind", "url", "level"),
81
+ "research": ("status", "started"),
82
+ }
83
+
84
+
85
+ def _key_facts(note_type: str, meta: Any) -> str | None:
86
+ """One line of the fields an agent needs to judge a note; missing fields are left out."""
87
+ if not isinstance(meta, dict) or note_type not in _KEY_FACTS:
88
+ return None
89
+ flag = " [disputed]" if note_type == "knowledge" and meta.get("disputed") else ""
90
+ return (
91
+ " \u00b7 ".join(
92
+ f"{k}: {meta[k]}{flag if k == 'confidence' else ''}"
93
+ for k in _KEY_FACTS[note_type]
94
+ if meta.get(k) is not None
95
+ )
96
+ or None
97
+ )
98
+
99
+
100
+ _LEAD_SECTION = {"knowledge": "Claim", "literature": "TL;DR"}
101
+
102
+
103
+ def snippet(
104
+ note: note_files.Note,
105
+ terms: Sequence[str] = (),
106
+ *,
107
+ weights: Mapping[str, float] | None = None,
108
+ width: int = 200,
109
+ ) -> str:
110
+ """The body line (not blank, heading, table separator or inside a fenced code block) with the highest
111
+ total weight of its distinct `terms` (`weights`, else 1 each), earliest on ties; else the first such line.
112
+ Whitespace is collapsed and text over `width` is cut with an ellipsis."""
113
+ body = note.body.splitlines()
114
+ fenced = link_rules._in_fence(body)
115
+ lines = [
116
+ line
117
+ for line, inside in zip(body, fenced, strict=False)
118
+ if not inside
119
+ and line.strip()
120
+ and not line.lstrip().startswith("#")
121
+ and not set(line.strip()) <= set("|-: ")
122
+ ]
123
+ if not lines:
124
+ return ""
125
+ wanted = set(terms)
126
+ weight = lambda line: sum(
127
+ 1.0 if weights is None else weights.get(t, 0.0)
128
+ for t in wanted & set(records.tokenize(line))
129
+ )
130
+ best = max(lines, key=weight) # max keeps the earliest tie
131
+ text = " ".join(best.split())
132
+ return text if len(text) <= width else text[: width - 1] + "\u2026"
133
+
134
+
135
+ class HitOptions(TypedDict, total=False):
136
+ """The keyword options of `format_hit`."""
137
+
138
+ score: float | None
139
+ terms: Sequence[str]
140
+ weights: Mapping[str, float] | None
141
+ name: str | None
142
+
143
+
144
+ def _hit_summary(note: note_files.Note) -> list[str]:
145
+ """The lead section of a note, indented, for the `summary` detail."""
146
+ body = note.body.splitlines()
147
+ lead = _LEAD_SECTION.get(note.type) or next(
148
+ (line[2:].strip() for _, level, line in _headings(body) if level == _SECTION_LEVEL),
149
+ None,
150
+ )
151
+ if lead is None:
152
+ return []
153
+ return [" " + line for line in _sections(body, [lead])[1:] if line.strip()]
154
+
155
+
156
+ def _hit_disputed(note: note_files.Note) -> bool:
157
+ return (
158
+ note.type == "knowledge" and isinstance(note.meta, dict) and bool(note.meta.get("disputed"))
159
+ )
160
+
161
+
162
+ def _hit_body_lines(note: note_files.Note, detail: str, options: HitOptions) -> list[str]:
163
+ """The lines under a hit for the `snippet` and `summary` details; none for the others."""
164
+ if detail == "summary":
165
+ return _hit_summary(note)
166
+ if detail == "snippet" and (
167
+ text := snippet(note, options.get("terms", ()), weights=options.get("weights"))
168
+ ):
169
+ return [" " + text]
170
+ return []
171
+
172
+
173
+ def format_hit(note: note_files.Note, detail: str, **options: Unpack[HitOptions]) -> list[str]:
174
+ """Output lines for one note at a `DETAILS` level; `score` is omitted from the line when None and
175
+ `name` (a short handle) replaces the path."""
176
+ name = options.get("name")
177
+ score = options.get("score")
178
+ if detail == "paths":
179
+ return [name or note.rel]
180
+ lines = [
181
+ (name or note.rel)
182
+ + ("" if score is None else f"\t{score:.2f}")
183
+ + f"\t{note_search._title(note)}"
184
+ ]
185
+ if detail == "titles":
186
+ if _hit_disputed(note):
187
+ lines[0] += " [disputed]"
188
+ return lines
189
+ if (facts := _key_facts(note.type, note.meta)) is not None:
190
+ lines.append(" " + facts)
191
+ lines.extend(_hit_body_lines(note, detail, options))
192
+ return lines
193
+
194
+
195
+ def short_handles(root: Path) -> dict[str, str]:
196
+ """Path -> the shortest prefix of its handle, cut at a hyphen and at least two words long, that no other
197
+ handle starts with (the whole handle when none is); `resolve_note` turns it back into the note."""
198
+ handles = {
199
+ rel: note_files._handle(rel)
200
+ for rel in (p.relative_to(root).as_posix() for _, p in note_files._note_files(root))
201
+ }
202
+ out = {}
203
+ for rel, handle in handles.items():
204
+ words = handle.split("-")
205
+ out[rel] = next(
206
+ (
207
+ pre
208
+ for k in range(2, len(words))
209
+ if sum(h.startswith(pre := "-".join(words[:k])) for h in handles.values()) == 1
210
+ ),
211
+ handle,
212
+ )
213
+ return out
214
+
215
+
216
+ _CONCLUSION = {
217
+ "knowledge": ("Claim", "Does not apply when"),
218
+ "literature": ("TL;DR",),
219
+ "research": ("Question",),
220
+ }
221
+
222
+
223
+ def _expand_conclusion(note_type: str, lines: list[str], sections: list[str]) -> list[str]:
224
+ """Replace `conclusion` by the note type's lead sections that exist; other kinds get their first `## `."""
225
+ present = [line[2:].strip() for _, level, line in _headings(lines) if level == _SECTION_LEVEL]
226
+ lead = [
227
+ n
228
+ for n in _CONCLUSION.get(note_type, present[:1])
229
+ if n.casefold() in {p.casefold() for p in present}
230
+ ]
231
+ return [
232
+ x for s in sections for x in (lead or [s] if s.strip().casefold() == "conclusion" else [s])
233
+ ]
234
+
235
+
236
+ def _outline_ranges(lines: list[str], body_line: int) -> list[str]:
237
+ """`<start>-<end><TAB><words>w<TAB><heading>` per heading; a section ends before the next heading of its level or higher."""
238
+ while lines and not lines[-1]:
239
+ lines = lines[:-1]
240
+ heads = _headings(lines)
241
+ rows = []
242
+ for n, (i, level, line) in enumerate(heads):
243
+ stop = next((j for j, lv, _ in heads[n + 1 :] if lv <= level), len(lines))
244
+ words = sum(len(x.split()) for x in lines[i:stop])
245
+ rows.append(f"{body_line + i}-{body_line + stop - 1}\t{words}w\t{line}")
246
+ return rows
247
+
248
+
249
+ @dataclass(frozen=True)
250
+ class _ShowMode:
251
+ """How `show` renders a body: whole, as an outline (with line ranges) or as chosen sections."""
252
+
253
+ sections: list[str] | None
254
+ outline: bool
255
+ ranges: bool
256
+
257
+
258
+ def _show_unresolved(arg: str, found: list[str] | None) -> str:
259
+ """The block for an argument that names no single note; prints the ambiguity to stderr."""
260
+ if found is None:
261
+ return f"== {arg}\n(not found)"
262
+ common._ambiguous(arg, found)
263
+ return f"== {arg}\n(ambiguous: {len(found)} notes match)"
264
+
265
+
266
+ def _show_header(note_type: str, meta: Any) -> list[str]:
267
+ """The lines before the body: what supersedes the note, its key facts and its synthesis."""
268
+ out = []
269
+ if isinstance(meta, dict) and isinstance(meta.get("superseded_by"), str):
270
+ out.append(f"superseded by: {meta['superseded_by']}")
271
+ if facts := _key_facts(note_type, meta):
272
+ out.append(facts)
273
+ if isinstance(meta, dict) and isinstance(meta.get("part_of"), str):
274
+ ref = "s:" + meta["part_of"]
275
+ out.append(f"part of: {ref} (extended version: mem show {ref})")
276
+ return out
277
+
278
+
279
+ def _show_body(note_type: str, body: str, body_line: int, mode: _ShowMode) -> list[str]:
280
+ lines = body.split("\n")
281
+ if mode.outline and mode.ranges:
282
+ return _outline_ranges(lines, body_line)
283
+ if mode.outline:
284
+ return [f"{body_line + i}: {line}" for i, _, line in _headings(lines)]
285
+ if mode.sections:
286
+ return _sections(lines, _expand_conclusion(note_type, lines, mode.sections))
287
+ return lines
288
+
289
+
290
+ def _show_note(path: Path, rel: str, mode: _ShowMode) -> tuple[str, bool]:
291
+ """The output block of one note and whether its file could be read."""
292
+ note_type = rel.split("/", 1)[0]
293
+ try:
294
+ text = note_files._read_text(path)
295
+ except note_files.FrontmatterError as exc:
296
+ return f"== {rel}\n({exc})", False
297
+ try:
298
+ meta, body, body_line = note_files.split_frontmatter(text)
299
+ except note_files.FrontmatterError:
300
+ meta, body, body_line = None, text, 1
301
+ out = [
302
+ f"== {rel}",
303
+ *_show_header(note_type, meta),
304
+ *_show_body(note_type, body, body_line, mode),
305
+ ]
306
+ return "\n".join(out).rstrip("\n"), True
307
+
308
+
309
+ def show(
310
+ root: Path,
311
+ paths: list[str],
312
+ *,
313
+ sections: list[str] | None = None,
314
+ outline: bool = False,
315
+ ranges: bool = False,
316
+ ) -> tuple[list[str], list[str], bool]:
317
+ """Blocks of output, one per path; the resolved paths shown; whether every path was found."""
318
+ mode = _ShowMode(sections, outline, ranges)
319
+ blocks: list[str] = []
320
+ shown: list[str] = []
321
+ ok = True
322
+ for arg in paths:
323
+ path = common.resolve_note(root, arg)
324
+ if not isinstance(path, Path):
325
+ blocks.append(_show_unresolved(arg, path))
326
+ ok = False
327
+ continue
328
+ rel = path.relative_to(root.resolve()).as_posix()
329
+ shown.append(rel)
330
+ block, readable = _show_note(path, rel, mode)
331
+ blocks.append(block)
332
+ ok = ok and readable
333
+ return blocks, shown, ok
334
+
335
+
336
+ def source_text(root: Path, rel: str) -> Path | None:
337
+ """The largest `.txt` (ties by name) of a literature note's `.sources/<note-stem>/` folder, else its largest `.md`."""
338
+ folder = root / common.SOURCES_DIR / Path(rel).stem
339
+ texts: list[Path] = []
340
+ for pattern in ("*.txt", "*.md"):
341
+ texts = (
342
+ [p for p in folder.glob(pattern) if p.is_file() and not p.is_symlink()]
343
+ if folder.is_dir()
344
+ else []
345
+ )
346
+ if texts:
347
+ break
348
+ return min(texts, key=lambda p: (-p.stat().st_size, p.name), default=None)
349
+
350
+
351
+ def passages(
352
+ text: str, query: str, *, count: int = 5, words: int = 500
353
+ ) -> tuple[int, list[tuple[int, int, str]]]:
354
+ """(word count, [(first, last, text)] of the `count` best windows by BM25 over this text, in document order).
355
+
356
+ Windows of `words` words start half a window apart (BM25 k1 1.2, b 0.75); the last ends at the text's end;
357
+ word numbers start at 1."""
358
+ tokens = text.split()
359
+ step = max(1, words // 2)
360
+ starts = []
361
+ for start in range(0, max(len(tokens), 1), step):
362
+ starts.append(start)
363
+ if start + words >= len(tokens):
364
+ break
365
+ wins = [" ".join(tokens[s : s + words]) for s in starts]
366
+ counts = [collections.Counter(records.tokenize(w)) for w in wins]
367
+ lengths = [sum(c.values()) for c in counts]
368
+ average = sum(lengths) / len(wins)
369
+ idf = {}
370
+ for term in dict.fromkeys(records.tokenize(query)):
371
+ n = sum(1 for c in counts if term in c)
372
+ idf[term] = math.log(1 + (len(wins) - n + 0.5) / (n + 0.5))
373
+ scored = []
374
+ for i, (c, length) in enumerate(zip(counts, lengths, strict=False)):
375
+ score = sum(
376
+ idf[t] * c[t] * 2.2 / (c[t] + 1.2 * (1 - 0.75 + 0.75 * length / average))
377
+ for t in idf
378
+ if c.get(t) and average
379
+ )
380
+ if score > 0:
381
+ scored.append((-score, i))
382
+ best = sorted(i for _, i in sorted(scored)[:count])
383
+ return len(tokens), [
384
+ (starts[i] + 1, min(starts[i] + words, len(tokens)), wins[i]) for i in best
385
+ ]
386
+
387
+
388
+ def _scopes(root: Path, paths: list[str]) -> list[str]:
389
+ """Hub-relative form of existing files or folders inside the hub; ValueError names the first that is not."""
390
+ out = []
391
+ for arg in paths:
392
+ path = (Path(arg) if Path(arg).is_absolute() else root / arg).resolve()
393
+ if not path.exists() or not path.is_relative_to(root.resolve()):
394
+ raise ValueError(f"no such file or folder in the hub: {arg}")
395
+ out.append(path.relative_to(root.resolve()).as_posix())
396
+ return out
397
+
398
+
399
+ def _in_scopes(rel: str, scopes: list[str]) -> bool:
400
+ return not scopes or any(s in {".", rel} or rel.startswith(s + "/") for s in scopes)
401
+
402
+
403
+ def _page_footer(offset: int, shown: int, total: int) -> None:
404
+ if shown and offset + shown < total:
405
+ print(
406
+ f"-- {offset + 1}-{offset + shown} of {total}; next: --offset {offset + shown} --",
407
+ file=sys.stderr,
408
+ )
409
+ elif not shown and offset:
410
+ print(f"-- offset {offset} is past the {total} matches --", file=sys.stderr)
411
+
412
+
413
+ def cmd_check(args: argparse.Namespace) -> int:
414
+ try:
415
+ scopes = _scopes(args.root, args.paths)
416
+ except ValueError as exc:
417
+ print(f"mem: {exc}", file=sys.stderr)
418
+ return 2
419
+ problems = [p for p in check_rules.check(args.root) if _in_scopes(p.path, scopes)]
420
+ for problem in problems:
421
+ print(problem)
422
+ return 1 if problems else 0
423
+
424
+
425
+ def cmd_index(args: argparse.Namespace) -> int:
426
+ try:
427
+ changed = index_files.apply_index(args.root)
428
+ except (note_files.FrontmatterError, OSError) as exc:
429
+ print(f"mem: cannot build the index: {exc}", file=sys.stderr)
430
+ return 1
431
+ for rel in changed:
432
+ print(f"updated {rel}")
433
+ return 0
434
+
435
+
436
+ def cmd_find(args: argparse.Namespace) -> int:
437
+ try:
438
+ notes = note_search._matching_notes(
439
+ args.root,
440
+ type=args.type,
441
+ topic=args.topic,
442
+ kind=args.kind,
443
+ status=args.status,
444
+ confidence=args.confidence,
445
+ level=args.level,
446
+ superseded=args.superseded,
447
+ )
448
+ except (note_files.FrontmatterError, OSError) as exc:
449
+ print(f"mem: cannot find: {exc}", file=sys.stderr)
450
+ return 1
451
+ page = sorted(notes, key=lambda n: n.rel)[args.offset : args.offset + args.limit]
452
+ names = short_handles(args.root) if args.handles else {}
453
+ for note in page:
454
+ print("\n".join(format_hit(note, args.detail, name=names.get(note.rel))))
455
+ _page_footer(args.offset, len(page), len(notes))
456
+ return 0
457
+
458
+
459
+ def topic_tree(root: Path, topic: str | None = None) -> list[tuple[int, str, int]]:
460
+ """(depth, id, notes) in tree order; notes counts what `find --topic <id>` returns, descendants included."""
461
+ known = note_files.load_topics(root)
462
+ if topic and topic not in known:
463
+ raise note_files.FrontmatterError(note_search._unknown_topic_message(topic, known))
464
+ counts: collections.Counter = collections.Counter()
465
+ for note in note_search._matching_notes(root):
466
+ listed = note.meta.get("topics")
467
+ direct = (
468
+ {t for t in listed if isinstance(t, str) and t in known}
469
+ if isinstance(listed, list)
470
+ else set()
471
+ )
472
+ counts.update(direct.union(*(note_files.ancestors(known, t) for t in direct)))
473
+ rows: list[tuple[int, str, int]] = []
474
+
475
+ def walk(tid: str, depth: int) -> None:
476
+ rows.append((depth, tid, counts[tid]))
477
+ for child in sorted(
478
+ t
479
+ for t in known
480
+ if note_files._parent(known, t) == tid and t not in {r[1] for r in rows}
481
+ ):
482
+ walk(child, depth + 1)
483
+
484
+ for tid in [topic] if topic else sorted(note_files.root_topics(known)):
485
+ walk(tid, 0)
486
+ return rows
487
+
488
+
489
+ def cmd_topics(args: argparse.Namespace) -> int:
490
+ try:
491
+ rows = topic_tree(args.root, args.topic)
492
+ except (note_files.FrontmatterError, OSError) as exc:
493
+ print(f"mem: cannot find: {exc}", file=sys.stderr)
494
+ return 1
495
+ for depth, tid, count in rows:
496
+ print(f"{' ' * depth}{tid}\t{count}")
497
+ return 0
498
+
499
+
500
+ def _memory_line(m: records.Memory, today: datetime.date) -> str:
501
+ dead = common._memory_status(m, today)
502
+ created = m.created.isoformat() if m.created else "undated"
503
+ claim = " ".join(m.claim.split()) # a hand-edited tab or newline must not add a column
504
+ return (
505
+ f"m:{m.handle}\t[memory: {m.kind}, observed {m.observed}, {created}{common._unconfirmed(m)}"
506
+ f"{', ' + dead if dead else ''}]\t{claim}"
507
+ )
508
+
509
+
510
+ def _memory_facts(m: records.Memory) -> str:
511
+ facts = f"kind: {m.kind} \u00b7 observed {m.observed} \u00b7 status {m.status} \u00b7 created {m.created.isoformat() if m.created else 'undated'}"
512
+ if m.valid_until:
513
+ facts += f" \u00b7 valid until {m.valid_until.isoformat()}"
514
+ if m.context:
515
+ facts += f" \u00b7 context: {m.context}"
516
+ return facts
517
+
518
+
519
+ def _memory_source_lines(m: records.Memory) -> list[str]:
520
+ out = []
521
+ if m.sources:
522
+ out.append(f"sources: {', '.join(m.sources)}")
523
+ if m.short:
524
+ out.append(f"short: {m.short}")
525
+ return out
526
+
527
+
528
+ def _memory_tail_lines(m: records.Memory) -> list[str]:
529
+ """The optional fields after the versions: what shortened it, why triage held it, its topic and load."""
530
+ fields = (
531
+ ("short_by", m.short_by),
532
+ ("held at triage", m.triage_reason),
533
+ ("topic", m.topic),
534
+ ("load", m.load),
535
+ )
536
+ return [f"{label}: {value}" for label, value in fields if value]
537
+
538
+
539
+ def _memory_claim_lines(m: records.Memory, sections: list[str] | None) -> list[str]:
540
+ """The claim, and the body unless the sections asked for are only the conclusion."""
541
+ out = ["", "## Claim", " ".join(m.claim.split())]
542
+ if (
543
+ not (sections and any(s.strip().casefold() == "conclusion" for s in sections))
544
+ and m.body.strip()
545
+ ):
546
+ out += ["", m.body.rstrip("\n")]
547
+ return out
548
+
549
+
550
+ def _memory_block(m: records.Memory, sections: list[str] | None) -> str:
551
+ out = [f"== m:{m.handle} ({m.scope})", _memory_facts(m), *_memory_source_lines(m)]
552
+ found = records.tallies(m)
553
+ ends = [t.since for t in found[1:]] + [datetime.date.today()]
554
+ out += [common._tally_line(t, end) for t, end in zip(found, ends, strict=False)]
555
+ out += _memory_tail_lines(m)
556
+ out += _memory_claim_lines(m, sections)
557
+ return "\n".join(out)
558
+
559
+
560
+ def _is_memory_arg(args: argparse.Namespace, arg: str) -> bool:
561
+ """`m:<handle>`, or a bare handle that names no note and does name a memory."""
562
+ if arg.startswith("m:"):
563
+ return True
564
+ if "/" in arg or arg.endswith(".md"):
565
+ return False
566
+ root = common._optional_store(args)
567
+ if root is not None and common.resolve_note(root, arg) is not None:
568
+ return False
569
+ return common._find_memory(args, arg) is not None
570
+
571
+
572
+ def _synthesis_section_block(
573
+ syn: document.Synthesis, handle: str, section: str, lines: list[str]
574
+ ) -> str | None:
575
+ """The text of one section of a synthesis; None after a message when it has no such section."""
576
+ found = [s for s in syn.sections if s.handle == section]
577
+ if not found:
578
+ print(f"mem: no section {section} in s:{handle}", file=sys.stderr)
579
+ return None
580
+ start = found[0].line - 1
581
+ stop = next((x.line - 1 for x in syn.sections if x.line > found[0].line), len(lines))
582
+ return "\n".join([f"== s:{handle}#{section}", *lines[start:stop]]).rstrip("\n")
583
+
584
+
585
+ def _synthesis_body_lines(args: argparse.Namespace, text: str, lines: list[str]) -> list[str]:
586
+ """The lines of a whole synthesis `mem show` prints: its outline, the chosen sections or the file."""
587
+ frontmatter = cast("re.Match[str]", document._FRONTMATTER.match(text)) # `syn` parsed this text
588
+ first = text[: frontmatter.end()].count("\n")
589
+ body = lines[first:]
590
+ if args.outline and not args.ranges:
591
+ return [f"{first + 1 + i}: {line}" for i, _, line in _headings(body)]
592
+ if args.section and not args.outline:
593
+ return _sections(body, args.section)
594
+ if args.all and not args.outline:
595
+ return lines
596
+ # a synthesis is long: the outline with ranges is the default, `--all` prints the file
597
+ return _outline_ranges(body, first + 1)
598
+
599
+
600
+ def _synthesis_block(args: argparse.Namespace, ref: str) -> str | None:
601
+ """`s:<h>` the whole file (or its outline or `--section`s), `s:<h>#<section handle>` one section; None after a message."""
602
+ handle, section = document.split_ref(ref)
603
+ path = document.path_of(args.root / document.SYNTHESES_DIR, handle)
604
+ if path is None or not path.is_file():
605
+ print(f"mem: no synthesis {ref}", file=sys.stderr)
606
+ return None
607
+ syn = document.load_one(path)
608
+ if syn.error:
609
+ print(f"mem: {path}: {syn.error}", file=sys.stderr)
610
+ return None
611
+ text = path.read_bytes().decode("utf-8", "replace")
612
+ if not args.stored: # a reader gets `[n]`, the note's place on the `Sources:` line, not the 29-token reference; line numbers stay
613
+ text = document.shown_file(text)
614
+ lines = text.split("\n")
615
+ if section is not None:
616
+ return _synthesis_section_block(syn, handle, section, lines)
617
+ out = [f"== s:{handle}", *_synthesis_body_lines(args, text, lines)]
618
+ return "\n".join(out).rstrip("\n")
619
+
620
+
621
+ def _project_synthesis_block(ref: str, memory_dir: Path, tree: Path) -> str:
622
+ """The outline of `p:NAME` or the text of `p:NAME#HANDLE`; ProjectSynthesisError when it does not exist."""
623
+ name, handle = common._split_part_ref(ref)
624
+ found = common._load_project_syntheses(memory_dir, name)
625
+ parts = found.get(name)
626
+ if parts is None:
627
+ raise project_syntheses.Unavailable(
628
+ f"no project synthesis {name!r}; parts that exist: {common._existing_parts(found)}"
629
+ )
630
+ if handle is None:
631
+ return "\n".join(common._part_line(name, p, tree) for p in parts)
632
+ part = next((p for p in parts if p.handle == handle), None)
633
+ if part is None:
634
+ raise project_syntheses.Unavailable(
635
+ f"no part {handle!r} in {name}; parts that exist: {common._existing_parts(found)}"
636
+ )
637
+ state = project_syntheses.describe(project_syntheses.freshness(tree, part.stamp))
638
+ s = part.stamp
639
+ stamp = project_syntheses._render_stamp(s.paths, s.date, s.commit)
640
+ return f"== p:{name}#{part.handle} ({state})\n{part.heading}\n\n{part.body}\n{stamp}"
641
+
642
+
643
+ @dataclasses.dataclass(frozen=True)
644
+ class _ShowPart:
645
+ """What showing one argument produced: its blocks, the paths shown, and whether it went well."""
646
+
647
+ blocks: list[str]
648
+ shown: list[str]
649
+ ok: bool
650
+ refused: bool = False
651
+
652
+
653
+ def _show_refused_options(args: argparse.Namespace) -> bool:
654
+ """Whether the options of `mem show` are refused (a message is already printed); `--ranges` alone exits."""
655
+ if args.ranges and not args.outline:
656
+ raise common.UsageError("--ranges needs --outline")
657
+ if args.outline and args.section:
658
+ print("mem: --outline and --section cannot be used together", file=sys.stderr)
659
+ return True
660
+ return bool(args.project) and common._other_projects([args.project], False) is None
661
+
662
+
663
+ def _show_project_handle(args: argparse.Namespace, arg: str) -> _ShowPart | None:
664
+ """A `p:` handle; None when there is no store to read it from."""
665
+ if (
666
+ args.project or args.section
667
+ ): # refused per handle, so other handles in the call are still shown
668
+ print(
669
+ f"mem: --project and --section do not apply to `p:` handles ({arg})",
670
+ file=sys.stderr,
671
+ )
672
+ return _ShowPart([f"== {arg}\n(not found)"], [], ok=False, refused=True)
673
+ context = common._project_synthesis_context()
674
+ if context is None:
675
+ return None
676
+ try:
677
+ return _ShowPart([_project_synthesis_block(arg, context[0], context[1])], [], ok=True)
678
+ except project_syntheses.ProjectSynthesisError as exc:
679
+ print(f"mem: {exc}", file=sys.stderr)
680
+ refused = not isinstance(exc, project_syntheses.Unavailable)
681
+ return _ShowPart([f"== {arg}\n(not found)"], [], ok=False, refused=refused)
682
+
683
+
684
+ def _show_memory_handle(args: argparse.Namespace, arg: str) -> _ShowPart:
685
+ found = common._find_memory(args, arg.removeprefix("m:"))
686
+ if found is None:
687
+ print(f"mem: no memory {arg}", file=sys.stderr)
688
+ return _ShowPart([f"== {arg}\n(not found)"], [], ok=False)
689
+ if found.error is not None:
690
+ print(f"mem: skipped {found.path}: {found.error}", file=sys.stderr)
691
+ return _ShowPart([], [], ok=False)
692
+ return _ShowPart([_memory_block(found, args.section)], [], ok=True)
693
+
694
+
695
+ def _show_one_arg(args: argparse.Namespace, arg: str) -> _ShowPart | None:
696
+ """One argument of a call that mixes handles and paths; None when the call must stop with exit 2."""
697
+ if arg.startswith("p:"):
698
+ return _show_project_handle(args, arg)
699
+ if arg.startswith("s:"):
700
+ block = _synthesis_block(args, arg)
701
+ return _ShowPart([block or f"== {arg}\n(not found)"], [], ok=block is not None)
702
+ if _is_memory_arg(args, arg):
703
+ return _show_memory_handle(args, arg)
704
+ return _ShowPart(
705
+ *show(args.root, [arg], sections=args.section, outline=args.outline, ranges=args.ranges)
706
+ )
707
+
708
+
709
+ def _show_mixed(args: argparse.Namespace) -> _ShowPart | None:
710
+ """A call with handles among its arguments, shown one by one; None when it must stop with exit 2."""
711
+ blocks: list[str] = []
712
+ shown: list[str] = []
713
+ ok, refused = True, False
714
+ for arg in args.paths:
715
+ part = _show_one_arg(args, arg)
716
+ if part is None:
717
+ return None
718
+ blocks += part.blocks
719
+ shown += part.shown
720
+ ok = ok and part.ok
721
+ refused = refused or part.refused
722
+ return _ShowPart(blocks, shown, ok, refused)
723
+
724
+
725
+ def cmd_show(args: argparse.Namespace) -> int:
726
+ if _show_refused_options(args):
727
+ return 2
728
+ if any(a.startswith(("s:", "p:")) or _is_memory_arg(args, a) for a in args.paths):
729
+ part = _show_mixed(args)
730
+ if part is None:
731
+ return 2
732
+ else:
733
+ part = _ShowPart(
734
+ *show(
735
+ args.root,
736
+ args.paths,
737
+ sections=args.section,
738
+ outline=args.outline,
739
+ ranges=args.ranges,
740
+ )
741
+ )
742
+ print("\n\n".join(part.blocks))
743
+ if part.ok:
744
+ common.log_usage(
745
+ args.root,
746
+ {
747
+ "cmd": "show",
748
+ "paths": list(dict.fromkeys(part.shown)),
749
+ "sections": args.section or [],
750
+ "outline": bool(args.outline),
751
+ },
752
+ )
753
+ return 2 if part.refused else 0 if part.ok else 1
754
+
755
+
756
+ def _stats_orphans(args: argparse.Namespace) -> int:
757
+ root = args.root
758
+ try:
759
+ scopes = _scopes(root, args.paths)
760
+ except ValueError as exc:
761
+ print(f"mem: {exc}", file=sys.stderr)
762
+ return 2
763
+ for path in link_rules.orphan_notes(root):
764
+ if _in_scopes(path, scopes):
765
+ print(path)
766
+ return 0
767
+
768
+
769
+ def _stats_topic_count(root: Path) -> int:
770
+ try:
771
+ return len(note_files.load_topics(root))
772
+ except note_files.FrontmatterError:
773
+ return 0
774
+
775
+
776
+ def _stats_note_lines(args: argparse.Namespace, notes: list[note_files.Note]) -> list[str]:
777
+ """The store line, the count per note type and per domain, and the syntheses line."""
778
+ root = args.root
779
+ lines = [f"store: {root} (from {getattr(args, 'root_source', None) or 'unknown'})"]
780
+ lines += [
781
+ f"{kind}: {sum(1 for n in notes if n.type == kind)}" for kind in index_files.INDEX_FOLDERS
782
+ ]
783
+ for kind in ("literature", "knowledge"):
784
+ domains = collections.Counter(n.path.parent.name for n in notes if n.type == kind)
785
+ lines += [f"{kind}/{domain}: {domains[domain]}" for domain in sorted(domains)]
786
+ synths = [s for s in document.load(root / document.SYNTHESES_DIR) if s.error is None]
787
+ if synths:
788
+ lines.insert(
789
+ len(index_files.INDEX_FOLDERS) + 1,
790
+ f"syntheses: {len(synths)} ({sum(len(s.parts) for s in synths)} parts)",
791
+ )
792
+ return lines
793
+
794
+
795
+ def _stats_memory_line(args: argparse.Namespace) -> str | None:
796
+ """The count of project and global memories, or None when the store holds none."""
797
+ today = datetime.date.today()
798
+ counts = [
799
+ records.load_memories(folder, scope) for scope, folder in common._memory_folders(args)
800
+ ]
801
+ if not any(counts):
802
+ return None
803
+ counts = [[m for m in group if not records.quarantined(m)] for group in counts]
804
+ live = sum(records.is_live(m, today) for group in counts for m in group)
805
+ return f"memories: {len(counts[0])} project, {len(counts[1])} global ({live} live)"
806
+
807
+
808
+ def _stats_usage_entries() -> int:
809
+ log_path = common._usage_log(os.environ)
810
+ try:
811
+ return 0 if log_path is None else log_path.read_bytes().count(b"\n")
812
+ except OSError:
813
+ return 0
814
+
815
+
816
+ def cmd_stats(args: argparse.Namespace) -> int:
817
+ root = args.root
818
+ if args.paths and not args.orphans:
819
+ raise common.UsageError("PATH needs --orphans")
820
+ if args.orphans:
821
+ return _stats_orphans(args)
822
+ notes = note_files.discover_notes(root)
823
+ topic_count = _stats_topic_count(root)
824
+ chars = 0
825
+ for note in notes:
826
+ chars += len(note.text)
827
+ lines = _stats_note_lines(args, notes)
828
+ memory_line = _stats_memory_line(args)
829
+ if memory_line is not None:
830
+ lines.insert(1, memory_line)
831
+ script = resources.MEM_PY.read_text(encoding="utf-8")
832
+ lines.append(f"orphans: {len(link_rules.orphan_notes(root))}")
833
+ lines += [
834
+ f"topics: {topic_count}",
835
+ f"characters: {chars}",
836
+ f"tokens: {chars // 4}",
837
+ f"mem.py lines: {len(script.splitlines())}",
838
+ ]
839
+ lines.append(f"usage log entries: {_stats_usage_entries()}")
840
+ print("\n".join(lines))
841
+ return 0
842
+
843
+
844
+ def _deeper_hit(ctx: _SearchContext, query: str, printed: int) -> bool:
845
+ """True when a --deep search would print more note lines than the default one did (`printed`)."""
846
+ try:
847
+ args = ctx.args
848
+ full = ctx.full_corpus
849
+ return (
850
+ len(
851
+ note_search.rank(full, query, limit=len(full.notes))[
852
+ args.offset : args.offset + args.limit
853
+ ]
854
+ )
855
+ > printed
856
+ )
857
+ except (note_files.FrontmatterError, OSError):
858
+ return False
859
+
860
+
861
+ @dataclass(frozen=True)
862
+ class _SearchContext:
863
+ """What every query of one `mem search` run shares: the corpus, the memories and the syntheses."""
864
+
865
+ args: argparse.Namespace
866
+ with_notes: bool
867
+ corpus: note_search.Corpus | None
868
+ names: dict[str, str]
869
+ memories: list[tuple[str, list[records.Memory]]]
870
+ other_memories: list[tuple[str, list[records.Memory]]]
871
+ all_syntheses: list[document.Synthesis]
872
+ default_type: str | None
873
+ filters: dict[str, Any]
874
+ today: datetime.date
875
+
876
+ @cached_property
877
+ def full_corpus(self) -> note_search.Corpus:
878
+ args = self.args
879
+ return note_search.build_corpus(
880
+ args.root,
881
+ topic=args.topic,
882
+ kind=args.kind,
883
+ status=args.status,
884
+ confidence=args.confidence,
885
+ level=args.level,
886
+ superseded=args.superseded,
887
+ )
888
+
889
+
890
+ @dataclass(frozen=True)
891
+ class _QueryHits:
892
+ """What one query found: notes, notes linked to them, memory handles printed and syntheses."""
893
+
894
+ result: list[tuple[note_files.Note, float]]
895
+ linked: list[tuple[note_files.Note, float]]
896
+ printed: list[str]
897
+ sections: list[tuple[document.Synthesis, document.Section]]
898
+
899
+
900
+ def _search_check_args(args: argparse.Namespace, queries: list[str]) -> None:
901
+ if not all(records.tokenize(q) for q in queries):
902
+ raise common.UsageError("query has no searchable words: use letters or digits")
903
+ if args.links and args.offset:
904
+ raise common.UsageError("--offset cannot be used with --links")
905
+
906
+
907
+ def _search_filters(args: argparse.Namespace) -> dict[str, Any]:
908
+ return {
909
+ k: getattr(args, k)
910
+ for k in ("type", "topic", "kind", "status", "confidence", "level")
911
+ if getattr(args, k) is not None
912
+ }
913
+
914
+
915
+ def _search_rank(
916
+ args: argparse.Namespace, queries: list[str], default_type: str | None
917
+ ) -> tuple[
918
+ note_search.Corpus | None,
919
+ list[list[tuple[note_files.Note, float]]],
920
+ list[list[tuple[note_files.Note, float]]],
921
+ ]:
922
+ """The corpus, and per query its ranked notes and the notes linked to them (none without notes)."""
923
+ if args.scope == "memories":
924
+ return None, [[] for _ in queries], [[] for _ in queries]
925
+ corpus = note_search.build_corpus(
926
+ args.root,
927
+ type=args.type or default_type,
928
+ topic=args.topic,
929
+ kind=args.kind,
930
+ status=args.status,
931
+ confidence=args.confidence,
932
+ level=args.level,
933
+ superseded=args.superseded,
934
+ )
935
+ ranks = [note_search.rank(corpus, q, limit=len(corpus.notes)) for q in queries]
936
+ linkeds = [
937
+ note_search.linked_notes(args.root, corpus, r, args.limit) if args.links else []
938
+ for r in ranks
939
+ ]
940
+ return corpus, ranks, linkeds
941
+
942
+
943
+ def _search_load_memories(
944
+ args: argparse.Namespace, others: list[tuple[str, Path]]
945
+ ) -> tuple[list[tuple[str, list[records.Memory]]], list[tuple[str, list[records.Memory]]]]:
946
+ """The memories of this project and the global ones, then those of the other projects asked for."""
947
+ memories: list[tuple[str, list[records.Memory]]] = []
948
+ other_memories: list[tuple[str, list[records.Memory]]] = []
949
+ for scope, folder in [
950
+ *common._memory_folders(args),
951
+ *((f"project: {n}", f) for n, f in others),
952
+ ]:
953
+ loaded = records.load_memories(folder, scope.split(":")[0])
954
+ for m in loaded:
955
+ if m.error is not None:
956
+ print(f"mem: skipped {m.path}: {m.error}", file=sys.stderr)
957
+ loaded = [m for m in loaded if not records.quarantined(m)]
958
+ (other_memories if ":" in scope else memories).append((scope, loaded))
959
+ return memories, other_memories
960
+
961
+
962
+ def _search_context(
963
+ args: argparse.Namespace,
964
+ corpus: note_search.Corpus | None,
965
+ filters: dict[str, Any],
966
+ others: list[tuple[str, Path]],
967
+ default_type: str | None,
968
+ ) -> _SearchContext:
969
+ with_notes = args.scope != "memories"
970
+ names = short_handles(args.root) if args.handles and with_notes else {}
971
+ today = datetime.date.today()
972
+ # memories stay out of any narrowed, paged or path-only note listing, unless they are all that was asked for
973
+ memories, other_memories = (
974
+ _search_load_memories(args, others)
975
+ if args.scope != "notes"
976
+ and not args.offset
977
+ and not filters
978
+ and (args.detail != "paths" or not with_notes)
979
+ else ([], [])
980
+ )
981
+ # like memories, syntheses stay out of any narrowed, paged or path-only listing; they follow the notes
982
+ all_syntheses = (
983
+ document.load(args.root / document.SYNTHESES_DIR)
984
+ if args.deep
985
+ and args.scope == "all"
986
+ and args.root is not None
987
+ and not args.offset
988
+ and not filters
989
+ and args.detail != "paths"
990
+ else []
991
+ )
992
+ return _SearchContext(
993
+ args=args,
994
+ with_notes=with_notes,
995
+ corpus=corpus,
996
+ names=names,
997
+ memories=memories,
998
+ other_memories=other_memories,
999
+ all_syntheses=all_syntheses,
1000
+ default_type=default_type,
1001
+ filters=filters,
1002
+ today=today,
1003
+ )
1004
+
1005
+
1006
+ def _search_print_memory_hits(ctx: _SearchContext, scope: str, hits: list[records.Memory]) -> None:
1007
+ if ctx.args.detail == "paths":
1008
+ print("\n".join(f"m:{m.handle}" for m in hits))
1009
+ else:
1010
+ print(f"-- memories ({scope}) --")
1011
+ print("\n".join(_memory_line(m, ctx.today) for m in hits))
1012
+
1013
+
1014
+ def _search_memory_hits(ctx: _SearchContext, query: str) -> tuple[list[str], bool]:
1015
+ """Print the memories matching `query`: their handles (this project and global), and whether any
1016
+ came from another project."""
1017
+ printed: list[str] = []
1018
+ from_others = False
1019
+ for scope, loaded in [*ctx.memories, *ctx.other_memories]:
1020
+ hits = records.match_memories(
1021
+ loaded,
1022
+ records.tokenize(query),
1023
+ ctx.today,
1024
+ tokenize=records.tokenize,
1025
+ limit=3,
1026
+ include_dead=ctx.args.all_memories,
1027
+ )
1028
+ if not hits:
1029
+ continue
1030
+ _search_print_memory_hits(ctx, scope, hits)
1031
+ if ":" in scope:
1032
+ from_others = True
1033
+ else:
1034
+ printed += [f"m:{m.handle}" for m in hits]
1035
+ return printed, from_others
1036
+
1037
+
1038
+ def _search_print_notes(
1039
+ ctx: _SearchContext,
1040
+ terms: list[str],
1041
+ weights: dict[str, float],
1042
+ hits: list[tuple[note_files.Note, float]],
1043
+ ) -> None:
1044
+ for note, score in hits:
1045
+ print(
1046
+ "\n".join(
1047
+ format_hit(
1048
+ note,
1049
+ ctx.args.detail,
1050
+ score=score,
1051
+ terms=terms,
1052
+ weights=weights,
1053
+ name=ctx.names.get(note.rel),
1054
+ )
1055
+ )
1056
+ )
1057
+
1058
+
1059
+ def _search_log(ctx: _SearchContext, query: str, hits: _QueryHits) -> None:
1060
+ args = ctx.args
1061
+ extra = {"links": True, "linked": [note.rel for note, _ in hits.linked]} if args.links else {}
1062
+ if hits.printed:
1063
+ extra["memories"] = hits.printed
1064
+ if args.project or args.all_projects:
1065
+ extra["projects"] = len(ctx.other_memories)
1066
+ if hits.sections:
1067
+ extra["syntheses"] = [f"s:{syn.handle}#{sec.handle}" for syn, sec in hits.sections]
1068
+ if args.deep:
1069
+ extra["deep"] = True
1070
+ common.log_usage(
1071
+ args.root,
1072
+ {
1073
+ "cmd": "search",
1074
+ "query": query,
1075
+ "limit": args.limit,
1076
+ "detail": args.detail,
1077
+ "filters": ctx.filters,
1078
+ "results": [note.rel for note, _ in hits.result],
1079
+ **extra,
1080
+ },
1081
+ )
1082
+
1083
+
1084
+ def _search_print_query(ctx: _SearchContext, query: str, hits: _QueryHits, found: bool) -> None:
1085
+ """Print the notes, the linked notes and the syntheses of one query after its memories."""
1086
+ args = ctx.args
1087
+ if ctx.with_notes and found and hits.result:
1088
+ print("-- notes --")
1089
+ if not hits.result and not found and not args.offset:
1090
+ print("no matches", file=sys.stderr)
1091
+ terms = records.tokenize(query)
1092
+ weights = note_search.term_idf(ctx.corpus, terms) if ctx.corpus is not None else {}
1093
+ _search_print_notes(ctx, terms, weights, hits.result)
1094
+ if hits.linked and args.detail != "paths":
1095
+ print("-- linked to the results above --")
1096
+ _search_print_notes(ctx, terms, weights, hits.linked)
1097
+ if hits.sections:
1098
+ print("-- syntheses (extended versions) --")
1099
+ for syn, sec in hits.sections:
1100
+ print(f"s:{syn.handle}#{sec.handle}\t{syn.title}: {sec.heading}")
1101
+
1102
+
1103
+ def _search_one(
1104
+ ctx: _SearchContext,
1105
+ query: str,
1106
+ ranked: list[tuple[note_files.Note, float]],
1107
+ linked: list[tuple[note_files.Note, float]],
1108
+ more: bool,
1109
+ ) -> bool:
1110
+ """Run one query; True when a --deep search would show more (`more` carries earlier queries)."""
1111
+ args = ctx.args
1112
+ result = ranked[args.offset : args.offset + args.limit]
1113
+ if args.also:
1114
+ print(f"== {query} ==")
1115
+ printed, from_others = _search_memory_hits(ctx, query)
1116
+ sections = synthesis_edit.match_sections(
1117
+ ctx.all_syntheses, records.tokenize(query), tokenize=records.tokenize
1118
+ )
1119
+ hits = _QueryHits(result, linked, printed, sections)
1120
+ _search_print_query(ctx, query, hits, bool(printed or from_others))
1121
+ if ctx.default_type and ctx.with_notes and len(result) < _SPARSE_HITS and not more:
1122
+ more = _deeper_hit(ctx, query, len(result))
1123
+ if not args.also and ctx.with_notes: # a footer names --offset, which applies to every query
1124
+ _page_footer(args.offset, len(result), len(ranked))
1125
+ _search_log(ctx, query, hits)
1126
+ return more
1127
+
1128
+
1129
+ def cmd_search(args: argparse.Namespace) -> int:
1130
+ queries = [args.query, *args.also]
1131
+ _search_check_args(args, queries)
1132
+ others = (
1133
+ common._other_projects(args.project, args.all_projects)
1134
+ if args.project or args.all_projects
1135
+ else []
1136
+ )
1137
+ if others is None:
1138
+ return 2
1139
+ filters = _search_filters(args)
1140
+ default_type = None if args.deep or args.type else "knowledge"
1141
+ try:
1142
+ corpus, ranks, linkeds = _search_rank(args, queries, default_type)
1143
+ except (note_files.FrontmatterError, OSError) as exc:
1144
+ print(f"mem: cannot search: {exc}", file=sys.stderr)
1145
+ return 1
1146
+ ctx = _search_context(args, corpus, filters, others, default_type)
1147
+ more = False
1148
+ for query, ranked, linked in zip(queries, ranks, linkeds, strict=False):
1149
+ more = _search_one(ctx, query, ranked, linked, more)
1150
+ if more:
1151
+ print("mem: more in sources and syntheses: repeat with --deep.", file=sys.stderr)
1152
+ return 0
1153
+
1154
+
1155
+ def cmd_passages(args: argparse.Namespace) -> int:
1156
+ if not records.tokenize(args.query):
1157
+ raise common.UsageError("query has no searchable words: use letters or digits")
1158
+ try:
1159
+ notes = {n.rel for n in note_files.discover_notes(args.root) if n.type == "literature"}
1160
+ except (note_files.FrontmatterError, OSError) as exc:
1161
+ print(f"mem: cannot read passages: {exc}", file=sys.stderr)
1162
+ return 1
1163
+ path = common.resolve_note(args.root, args.path) # a path or handle, like `show`
1164
+ if isinstance(path, list):
1165
+ common._ambiguous(args.path, path)
1166
+ return 1
1167
+ rel = path.relative_to(args.root.resolve()).as_posix() if path else args.path
1168
+ source = source_text(args.root, rel) if rel in notes else None
1169
+ if source is None:
1170
+ print(
1171
+ f"mem: no source text for {args.path}: looked for a .txt in "
1172
+ f"{common.SOURCES_DIR}/{Path(rel).stem}/ (needs a literature note path); `mem fetch-sources {args.path}` "
1173
+ "downloads the source when it has a url, and writes a .txt only for a plain-text response "
1174
+ "or a PDF with pdftotext installed",
1175
+ file=sys.stderr,
1176
+ )
1177
+ return 1
1178
+ total, found = passages(
1179
+ source.read_text(encoding="utf-8", errors="replace"),
1180
+ args.query,
1181
+ count=args.count,
1182
+ words=args.words,
1183
+ )
1184
+ if not found:
1185
+ print(
1186
+ f"no matching passage in {source.relative_to(args.root).as_posix()} ({total} words)",
1187
+ file=sys.stderr,
1188
+ )
1189
+ else:
1190
+ print(f"source: {source.relative_to(args.root).as_posix()} ({total} words)")
1191
+ print("\n\n".join(f"== words {a}-{b} of {total} ==\n{t}" for a, b, t in found))
1192
+ common.log_usage(
1193
+ args.root,
1194
+ {
1195
+ "cmd": "passages",
1196
+ "path": rel,
1197
+ "query": args.query,
1198
+ "count": args.count,
1199
+ "words": args.words,
1200
+ "hits": len(found),
1201
+ },
1202
+ )
1203
+ return 0
1204
+
1205
+
1206
+ def _related_load(
1207
+ args: argparse.Namespace, rel: str | None
1208
+ ) -> tuple[note_search.Corpus, dict[str, list[note_files.Note]]]:
1209
+ corpus = note_search.build_corpus(args.root, superseded=args.superseded)
1210
+ if rel is None:
1211
+ raise ValueError(f"not a note: {rel}") # what `related` raises for it
1212
+ return corpus, note_search.related(args.root, rel, limit=args.limit, corpus=corpus)
1213
+
1214
+
1215
+ def _related_print(
1216
+ args: argparse.Namespace,
1217
+ rel: str,
1218
+ corpus: note_search.Corpus,
1219
+ groups: dict[str, list[note_files.Note]],
1220
+ ) -> None:
1221
+ terms = records.tokenize(note_search._title(next(n for n in corpus.notes if n.rel == rel)))
1222
+ weights = note_search.term_idf(corpus, terms)
1223
+ if args.unlinked_mentions:
1224
+ groups = {"mentions": note_search.unlinked_mentions(args.root, rel, corpus)}
1225
+ for relation, notes in groups.items():
1226
+ for other in notes:
1227
+ first, *rest = format_hit(other, args.detail, terms=terms, weights=weights)
1228
+ print("\n".join([f"{relation}\t{first}", *rest]))
1229
+ print(
1230
+ " · ".join(f"{relation}: {len(notes)}" for relation, notes in groups.items()),
1231
+ file=sys.stderr,
1232
+ )
1233
+
1234
+
1235
+ def cmd_related(args: argparse.Namespace) -> int:
1236
+ path = common.resolve_note(args.root, args.path)
1237
+ if isinstance(path, list):
1238
+ common._ambiguous(args.path, path)
1239
+ return 1
1240
+ rel = path.relative_to(args.root.resolve()).as_posix() if path else None
1241
+ try:
1242
+ corpus, groups = _related_load(args, rel)
1243
+ except ValueError:
1244
+ print(f"mem: not a note: {args.path}", file=sys.stderr)
1245
+ return 1
1246
+ except (note_files.FrontmatterError, OSError) as exc:
1247
+ print(f"mem: cannot relate: {exc}", file=sys.stderr)
1248
+ return 1
1249
+ assert rel is not None # `_related_load` raised for a missing note
1250
+ _related_print(args, rel, corpus, groups)
1251
+ return 0
1252
+
1253
+
1254
+ def cmd_search_eval(args: argparse.Namespace) -> int:
1255
+ try:
1256
+ outcome = note_search.search_eval(args.root)
1257
+ except (note_files.FrontmatterError, OSError) as exc:
1258
+ print(f"mem: cannot evaluate search: {exc}", file=sys.stderr)
1259
+ return 1
1260
+ if outcome is None:
1261
+ print(f"mem: {note_search._EVAL_FILE} not found", file=sys.stderr)
1262
+ return 0
1263
+ misses, found, expected, reciprocal = outcome
1264
+ for miss in misses:
1265
+ print(miss)
1266
+ recall = found / expected if expected else 1.0
1267
+ print(f"recall@10: {recall:.2f} ({found}/{expected})")
1268
+ mrr = reciprocal / expected if expected else 1.0
1269
+ print(f"MRR@10: {mrr:.3f}")
1270
+ if args.min is not None:
1271
+ return 1 if recall < args.min else 0
1272
+ if recall < RECALL_TRIGGER or mrr < MRR_TRIGGER:
1273
+ print(
1274
+ f"search-eval: below the revisit trigger (recall@10 {RECALL_TRIGGER:.2f}, MRR@10 {MRR_TRIGGER:.3f}): "
1275
+ "see C-6 in docs/requirements.md",
1276
+ file=sys.stderr,
1277
+ )
1278
+ return 1
1279
+ return 0
1280
+
1281
+
1282
+ def cmd_review(args: argparse.Namespace) -> int:
1283
+ today = args.today or datetime.date.today()
1284
+ for line in (
1285
+ due_queries.due_requirements(args.root, today)
1286
+ + due_queries.due_retests(args.root, today)
1287
+ + due_queries.due_rereads(args.root, today)
1288
+ ):
1289
+ print(line)
1290
+ return 0