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,766 @@
1
+ """The `fetch-sources` and `import` handlers (A5, ADR 0028): downloads, HTML and PDF text extraction, and the store import.
2
+
3
+ `mem.py` imports it at start-up like every command module (a local import is forbidden by Ruff; ADR 0028), so
4
+ `http.client` and `html.parser` load on every run, about 18 ms."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import collections
9
+ import contextlib
10
+ import html.parser
11
+ import http.client
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ import time
19
+ import urllib.parse
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING
23
+
24
+ import yaml
25
+
26
+ from memory_cli.commands import common, edit, import_recovery
27
+ from memory_cli.core import safe_io
28
+ from memory_cli.memories import records
29
+ from memory_cli.notes import check as check_rules
30
+ from memory_cli.notes import index as index_files
31
+ from memory_cli.notes import note as note_files
32
+ from memory_cli.research import checks as research_checks
33
+
34
+ if TYPE_CHECKING:
35
+ import argparse
36
+ from collections.abc import Sequence
37
+
38
+ from memory_cli.notes import fields as note_fields
39
+
40
+
41
+ FETCH_TIMEOUT = 30 # seconds per socket operation: slow source servers answer late
42
+
43
+
44
+ FETCH_DEADLINE = 120 # seconds for one download, all redirects together
45
+
46
+
47
+ FETCH_PAUSE = 1.0
48
+
49
+
50
+ FETCH_MAX_BYTES = 50 * 1024 * 1024 # larger sources stay online only (C-14)
51
+
52
+
53
+ _USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"
54
+
55
+
56
+ _CONTENT_EXT = {
57
+ "application/pdf": "pdf",
58
+ "text/html": "html",
59
+ "application/xhtml+xml": "html",
60
+ "text/plain": "txt",
61
+ }
62
+
63
+
64
+ _SUFFIX_EXT = {".pdf": "pdf", ".html": "html", ".htm": "html", ".txt": "txt"}
65
+
66
+
67
+ def _download(url: str) -> tuple[bytes, str]:
68
+ """(body, Content-Type) of a URL, redirects followed. Goes through the address-checked transport of
69
+ `research_checks`: a host that resolves to a non-public address, at any hop, is refused."""
70
+ try:
71
+ return research_checks.fetch_raw(
72
+ url,
73
+ lambda _: FETCH_MAX_BYTES,
74
+ over="fail",
75
+ headers={"User-Agent": _USER_AGENT, "Accept": "*/*"},
76
+ deadline=FETCH_DEADLINE,
77
+ max_redirects=10,
78
+ timeout=FETCH_TIMEOUT,
79
+ )
80
+ except research_checks.FetchError as exc:
81
+ raise ValueError(str(exc)) from exc
82
+
83
+
84
+ def _source_extension(url: str, content_type: str) -> str:
85
+ mime = content_type.split(";", 1)[0].strip().lower()
86
+ if mime in _CONTENT_EXT:
87
+ return _CONTENT_EXT[mime]
88
+ suffix = Path(urllib.parse.urlparse(url).path).suffix.lower()
89
+ return _SUFFIX_EXT.get(suffix, "html")
90
+
91
+
92
+ _SKIP_TAGS = {
93
+ "script",
94
+ "style",
95
+ "noscript",
96
+ "nav",
97
+ "header",
98
+ "footer",
99
+ "aside",
100
+ "svg",
101
+ "title",
102
+ "select",
103
+ "button",
104
+ "option",
105
+ }
106
+
107
+
108
+ _BLOCK_TAGS = {
109
+ "p",
110
+ "div",
111
+ "br",
112
+ "li",
113
+ "tr",
114
+ "h1",
115
+ "h2",
116
+ "h3",
117
+ "h4",
118
+ "h5",
119
+ "h6",
120
+ "table",
121
+ "section",
122
+ "article",
123
+ "blockquote",
124
+ "pre",
125
+ }
126
+
127
+
128
+ _CHARSET = re.compile(rb"""charset\s*=\s*["']?([\w.:-]+)""", re.IGNORECASE)
129
+
130
+
131
+ MIN_TEXT_WORDS = (
132
+ 200 # a shorter conversion is a shell page (script-rendered, paywalled), not a source text
133
+ )
134
+
135
+
136
+ class _TextExtractor(html.parser.HTMLParser):
137
+ def __init__(self) -> None:
138
+ super().__init__(convert_charrefs=True)
139
+ self.out: list[str] = []
140
+ self.skip: list[str] = []
141
+ self.main = 0 # open article/main elements: a header inside one is part of the text
142
+
143
+ def handle_starttag(self, tag: str, attrs: list) -> None:
144
+ self.main += tag in {"article", "main"}
145
+ if tag in _SKIP_TAGS and not (tag == "header" and self.main):
146
+ self.skip.append(tag)
147
+ if tag in _BLOCK_TAGS:
148
+ self.out.append("\n")
149
+
150
+ def handle_endtag(self, tag: str) -> None:
151
+ self.main = max(0, self.main - (tag in {"article", "main"}))
152
+ if tag in self.skip:
153
+ del self.skip[len(self.skip) - 1 - self.skip[::-1].index(tag) :]
154
+ if tag in _BLOCK_TAGS:
155
+ self.out.append("\n")
156
+
157
+ def handle_data(self, data: str) -> None:
158
+ if not self.skip:
159
+ self.out.append(
160
+ re.sub(r"\s+", " ", data)
161
+ ) # a newline inside the markup is not a line break
162
+
163
+
164
+ def html_to_text(data: bytes) -> str:
165
+ """Plain text of an HTML document: no script, style or page chrome; one line per block, spaces collapsed.
166
+
167
+ Charset from a `<meta>` in the first 4,096 bytes, else UTF-8, latin-1 when that fails to decode."""
168
+ match = _CHARSET.search(data[:4096])
169
+ try:
170
+ text = data.decode(match.group(1).decode("ascii") if match else "utf-8")
171
+ except (UnicodeDecodeError, LookupError):
172
+ text = data.decode("latin-1")
173
+ parser = _TextExtractor()
174
+ parser.feed(text)
175
+ parser.close()
176
+ lines = [" ".join(line.split()) for line in "".join(parser.out).split("\n")]
177
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + "\n"
178
+
179
+
180
+ def _literature_notes(
181
+ root: Path, paths: list[str] | None
182
+ ) -> tuple[list[note_files.Note], list[str]]:
183
+ """The literature notes to work on (all, or the given paths) and a `failed` line per path that is not one."""
184
+ notes = [n for n in note_files.discover_notes(root) if n.type == "literature"]
185
+ if not paths:
186
+ return notes, []
187
+ by_rel = {n.rel: n for n in notes}
188
+ return (
189
+ [by_rel[p] for p in paths if p in by_rel],
190
+ [f"failed {p}: not a literature note" for p in paths if p not in by_rel],
191
+ )
192
+
193
+
194
+ def _txt_files(folder: Path) -> list[Path]:
195
+ """Every `.txt` entry of a source folder (any case, symlinks too): the hub never writes `source.txt` beside one."""
196
+ return [p for p in folder.iterdir() if p.suffix.lower() == ".txt"]
197
+
198
+
199
+ def _largest_copy(folder: Path, *patterns: str) -> Path | None:
200
+ """The largest regular file of the folder matching a pattern (ties by name), symlinks left out."""
201
+ found = [p for pat in patterns for p in folder.glob(pat) if p.is_file() and not p.is_symlink()]
202
+ return max(found, key=lambda p: (p.stat().st_size, p.name), default=None)
203
+
204
+
205
+ def _text_from_page(folder: Path, page: Path) -> str | None:
206
+ """Write `source.txt` from an HTML copy: None when written, else the reason it is too short."""
207
+ text = html_to_text(page.read_bytes())
208
+ if len(text.split()) >= MIN_TEXT_WORDS:
209
+ safe_io.replace_file(folder / "source.txt", text.encode("utf-8"))
210
+ return None
211
+ return f"page has under {MIN_TEXT_WORDS} words of text"
212
+
213
+
214
+ def _text_from_pdf(folder: Path, pdf: Path) -> str | None:
215
+ """Write `source.txt` from a PDF copy with `pdftotext`: None when written, else the reason."""
216
+ if not shutil.which("pdftotext"):
217
+ return "pdftotext is not installed"
218
+ try:
219
+ done = subprocess.run(
220
+ ["pdftotext", str(pdf), str(folder / "source.txt")],
221
+ check=False,
222
+ timeout=60,
223
+ capture_output=True,
224
+ )
225
+ except (OSError, subprocess.SubprocessError) as exc:
226
+ return f"pdftotext failed: {exc}"
227
+ if done.returncode == 0:
228
+ return None
229
+ (folder / "source.txt").unlink(missing_ok=True)
230
+ return f"pdftotext failed with exit {done.returncode}"
231
+
232
+
233
+ def _write_text_copy(folder: Path) -> str | None:
234
+ """Write `source.txt` from the folder's largest HTML copy, else its largest PDF; None when written, else the reason."""
235
+ if _txt_files(folder):
236
+ return "the folder already holds a .txt"
237
+ reason = "no HTML or PDF copy"
238
+ if (page := _largest_copy(folder, "*.html", "*.htm")) is not None:
239
+ reason = _text_from_page(folder, page)
240
+ if reason is None:
241
+ return None
242
+ if (pdf := _largest_copy(folder, "*.pdf")) is None:
243
+ return reason
244
+ return _text_from_pdf(folder, pdf)
245
+
246
+
247
+ def _folder_text_status(folder: Path) -> tuple[str | None, int] | None:
248
+ """(reason it has no text, words of its text) for a source folder after trying to build `source.txt`;
249
+ None when the folder already held a `.txt`."""
250
+ if folder.is_symlink():
251
+ return f"{common.SOURCES_DIR}/{folder.name} is a symlink", 0
252
+ if _txt_files(folder):
253
+ return None
254
+ reason = _write_text_copy(folder)
255
+ if reason is not None:
256
+ return reason, 0
257
+ return None, len((folder / "source.txt").read_text(encoding="utf-8").split())
258
+
259
+
260
+ def build_missing_texts(root: Path, paths: list[str] | None = None) -> tuple[list[str], bool]:
261
+ """`fetch-sources --text-only`: write `source.txt` in each `.sources/<stem>/` folder that holds no `.txt`.
262
+
263
+ Never downloads, never touches a folder with any `.txt` (hand-made texts win in `passages`) and skips a
264
+ folder that is a symlink. Returns (output lines, False when a PATH is not a literature note)."""
265
+ notes, lines = _literature_notes(root, paths)
266
+ bad = bool(lines)
267
+ written = without = had = 0
268
+ for note in notes:
269
+ folder = root / common.SOURCES_DIR / note.path.stem
270
+ if not folder.is_dir():
271
+ continue
272
+ try:
273
+ status = _folder_text_status(folder)
274
+ except OSError as exc:
275
+ status = (str(exc), 0)
276
+ if status is None:
277
+ had += 1
278
+ continue
279
+ reason, words = status
280
+ if reason is None:
281
+ lines.append(f"text {note.rel} ({words} words)")
282
+ written += 1
283
+ else:
284
+ lines.append(f"no text {note.rel}: {reason}")
285
+ without += 1
286
+ lines.append(f"text written {written}, without text {without}, already had text {had}")
287
+ return lines, not bad
288
+
289
+
290
+ @dataclass(frozen=True)
291
+ class _FetchOutcome:
292
+ """What `fetch_sources` did with one note: the counter to bump, the output line, whether it hit the network."""
293
+
294
+ counter: str
295
+ line: str
296
+ requested: bool
297
+
298
+
299
+ def _fetch_refusal(note: note_files.Note, folder: Path, force: bool) -> tuple[str, str] | None:
300
+ """(counter, output line) when a note's folder rules out a download: a symlink or a cached copy."""
301
+ if folder.is_symlink():
302
+ return "failed", f"failed {note.rel}: {common.SOURCES_DIR}/{folder.name} is a symlink"
303
+ if not force and folder.is_dir() and any(not p.is_symlink() for p in folder.iterdir()):
304
+ return "skipped", f"skipped {note.rel} (already cached)"
305
+ return None
306
+
307
+
308
+ def _http_url(note: note_files.Note) -> str | None:
309
+ """The note's `url` when it is a string starting with http:// or https://."""
310
+ url = note.meta.get("url") if isinstance(note.meta, dict) else None
311
+ if isinstance(url, str) and urllib.parse.urlparse(url).scheme in {"http", "https"}:
312
+ return url
313
+ return None
314
+
315
+
316
+ def _download_source(folder: Path, url: str) -> str:
317
+ """Download `url` into `folder` as `source.<ext>`, dropping other copies of `source.*`; the extension."""
318
+ data, content_type = _download(url)
319
+ ext = _source_extension(url, content_type)
320
+ folder.mkdir(parents=True, exist_ok=True)
321
+ if ext == "txt" and any(p.name != "source.txt" for p in _txt_files(folder)):
322
+ raise ValueError("the folder already holds a .txt")
323
+ for old in folder.glob("source.*"): # --force: drop copies of another type or a stale text
324
+ old.unlink()
325
+ safe_io.replace_file(folder / f"source.{ext}", data)
326
+ return ext
327
+
328
+
329
+ def _fetched_line(note: note_files.Note, folder: Path, ext: str) -> str:
330
+ """The output line of a fetched note; an HTML copy is converted to text, and a failure noted."""
331
+ if ext == "pdf" and shutil.which("pdftotext") and not _txt_files(folder):
332
+ with contextlib.suppress(OSError, subprocess.SubprocessError):
333
+ subprocess.run(
334
+ ["pdftotext", str(folder / "source.pdf"), str(folder / "source.txt")],
335
+ check=False,
336
+ timeout=60,
337
+ capture_output=True,
338
+ )
339
+ line = f"fetched {note.rel}"
340
+ if ext != "html":
341
+ return line
342
+ try:
343
+ reason = _write_text_copy(folder)
344
+ except OSError as exc:
345
+ reason = str(exc)
346
+ return line if reason is None else f"{line} (no text: {reason})"
347
+
348
+
349
+ def _fetch_one(note: note_files.Note, folder: Path, force: bool, pause: bool) -> _FetchOutcome:
350
+ """Download one note's source, sleeping first when `pause` (a request went out before)."""
351
+ if (refusal := _fetch_refusal(note, folder, force)) is not None:
352
+ return _FetchOutcome(*refusal, requested=False)
353
+ url = _http_url(note)
354
+ if url is None:
355
+ line = f"failed {note.rel}: url must start with http:// or https://"
356
+ return _FetchOutcome("failed", line, requested=False)
357
+ if pause:
358
+ time.sleep(FETCH_PAUSE)
359
+ try:
360
+ ext = _download_source(folder, url)
361
+ except (OSError, ValueError, http.client.HTTPException) as exc:
362
+ return _FetchOutcome("failed", f"failed {note.rel}: {exc}", requested=True)
363
+ return _FetchOutcome("fetched", _fetched_line(note, folder, ext), requested=True)
364
+
365
+
366
+ def fetch_sources(
367
+ root: Path, paths: list[str] | None = None, *, force: bool = False
368
+ ) -> tuple[list[str], bool]:
369
+ """Download each literature note's `url` into .sources/<note-stem>/; returns (output lines, all ok)."""
370
+ notes, lines = _literature_notes(root, paths)
371
+ counts = {"fetched": 0, "skipped": 0, "failed": len(lines)}
372
+ requested = False
373
+ for note in notes:
374
+ outcome = _fetch_one(note, root / common.SOURCES_DIR / note.path.stem, force, requested)
375
+ lines.append(outcome.line)
376
+ counts[outcome.counter] += 1
377
+ requested = requested or outcome.requested
378
+ lines.append(
379
+ f"fetched {counts['fetched']}, skipped {counts['skipped']}, failed {counts['failed']}"
380
+ )
381
+ return lines, counts["failed"] == 0
382
+
383
+
384
+ _IMPORT_FOLDERS = ("literature", "knowledge", "research")
385
+
386
+
387
+ # what an investigation's documents are made of: the text and the figures it embeds
388
+ _IMPORT_DOCUMENTS = {".md", ".png", ".jpg", ".jpeg", ".svg", ".gif", ".webp"}
389
+
390
+
391
+ def _import_refused(src: Path, path: Path, skipped: list[str]) -> bool:
392
+ """Whether the path is a symlink or under one; its source-relative path then goes to `skipped`."""
393
+ try:
394
+ safe_io.refuse_symlink_chain(src, path)
395
+ except safe_io.UnsafePath:
396
+ skipped.append(path.relative_to(src).as_posix())
397
+ return True
398
+ return False
399
+
400
+
401
+ def _import_subdirs(
402
+ src: Path, here: str, dirs: list[str], top: str, skipped: list[str]
403
+ ) -> list[str]:
404
+ """The folders of `here` an import descends into, sorted: no hidden one (but under `.sources`), no cache, no symlink."""
405
+ kept = sorted(d for d in dirs if d == d.lstrip(".") or top == ".sources")
406
+ return [
407
+ d for d in kept if d != "__pycache__" and not _import_refused(src, Path(here) / d, skipped)
408
+ ]
409
+
410
+
411
+ def _import_keeps(rel: Path, top: str, research_data: bool) -> bool:
412
+ """Whether an import lists the file: not a hidden one (but under `.sources`), not an investigation's data or
413
+ code unless asked, not a generated listing."""
414
+ name = rel.name
415
+ if top != ".sources" and name.startswith("."):
416
+ return False
417
+ # An investigation's data and code stay where the experiments live; its documents are the memory.
418
+ if (
419
+ top == "research"
420
+ and not research_data
421
+ and Path(name).suffix.lower() not in _IMPORT_DOCUMENTS
422
+ ):
423
+ return False
424
+ # the generated listings: folder/README.md and, for literature and knowledge, folder/topic/README.md
425
+ return not (
426
+ name == "README.md"
427
+ and top != ".sources"
428
+ and len(rel.parts) in ((2,) if top == "research" else (2, 3))
429
+ )
430
+
431
+
432
+ def _import_listed(src: Path, top: str, research_data: bool, skipped: list[str]) -> list[str]:
433
+ """The source-relative paths of one top folder an import lists."""
434
+ found: list[str] = []
435
+ for here, dirs, names in os.walk(src / top):
436
+ dirs[:] = _import_subdirs(src, here, dirs, top, skipped)
437
+ for name in names:
438
+ if _import_refused(src, Path(here) / name, skipped):
439
+ continue
440
+ rel = (Path(here) / name).relative_to(src)
441
+ if _import_keeps(rel, top, research_data):
442
+ found.append(rel.as_posix())
443
+ return found
444
+
445
+
446
+ def _import_files(
447
+ src: Path, with_sources: bool, research_data: bool = False, skipped: list[str] | None = None
448
+ ) -> list[str]:
449
+ """Source-relative paths to import, sorted. The source is only listed and read, never written.
450
+ A symlink, or anything under one, is never listed: its source-relative path goes to `skipped`."""
451
+ skipped = skipped if skipped is not None else []
452
+ found: list[str] = []
453
+ roots = [*_IMPORT_FOLDERS, *([".sources"] if with_sources else [])]
454
+ for top in roots:
455
+ if (src / top).is_symlink():
456
+ _import_refused(src, src / top, skipped)
457
+ continue
458
+ found += _import_listed(src, top, research_data, skipped)
459
+ return sorted(found)
460
+
461
+
462
+ def _note_kind(rel: str) -> str | None:
463
+ parts = rel.split("/")
464
+ if (
465
+ parts[0] in {"literature", "knowledge"}
466
+ and len(parts) == edit._NOTE_PATH_PARTS
467
+ and parts[2].endswith(".md")
468
+ and parts[2] != "README.md"
469
+ ):
470
+ return parts[0]
471
+ if parts[0] == "research" and len(parts) == edit._NOTE_PATH_PARTS and parts[2] == "README.md":
472
+ return "research"
473
+ return None
474
+
475
+
476
+ def _import_text(src: Path, rel: str) -> str | None:
477
+ """The text of an imported file; None when it cannot be read or is binary (a NUL byte)."""
478
+ try:
479
+ raw = (src / rel).read_bytes()
480
+ except OSError:
481
+ return None
482
+ if raw[:2] in {b"\xff\xfe", b"\xfe\xff"}: # a BOM-marked UTF-16 file holds NULs but is text
483
+ return raw.decode("utf-16", errors="ignore")
484
+ if b"\x00" in raw:
485
+ return None
486
+ return raw.decode("utf-8", errors="ignore")
487
+
488
+
489
+ def _import_hard_terms() -> list[records.Term]:
490
+ """The hard terms of the forbidden list; none when it cannot be read."""
491
+ try:
492
+ return [t for t in records.read_terms(os.environ) if not t.soft]
493
+ except records.ForbiddenListError:
494
+ return []
495
+
496
+
497
+ def _flag_import(src: Path, files: Sequence[str]) -> list[str]:
498
+ """Imported text files whose text matches a secret pattern or a hard term (a file with a NUL byte is binary: skipped)."""
499
+ terms = _import_hard_terms()
500
+ flagged = []
501
+ for rel in files:
502
+ text = _import_text(src, rel)
503
+ if text is None:
504
+ continue
505
+ if records.secret_in([text]) is not None or (
506
+ terms and any(not t.soft for t in records.term_hits([text], os.environ))
507
+ ):
508
+ flagged.append(rel)
509
+ return flagged
510
+
511
+
512
+ def _union_topics(src: Path, dest: Path) -> tuple[list[str], list[str], str]:
513
+ """(ids added, ids kept as they were, text to append to the destination's topics.yaml)."""
514
+ path = src / "topics.yaml"
515
+ if path.is_symlink() or not path.is_file():
516
+ return [], [], ""
517
+ try:
518
+ theirs = note_files.load_yaml(note_files._read_text(path))
519
+ except (yaml.YAMLError, note_files.FrontmatterError) as exc:
520
+ raise note_files.FrontmatterError(f"the source's topics.yaml is unusable ({exc})") from exc
521
+ if theirs is None:
522
+ theirs = {}
523
+ if not isinstance(theirs, dict):
524
+ raise note_files.FrontmatterError("the source's topics.yaml must be a mapping of topic ids")
525
+ mine = note_files.load_topics(dest)
526
+ added = [t for t in theirs if t not in mine]
527
+ kept = [t for t in theirs if t in mine and theirs[t] != mine[t]]
528
+ # one `id: {flow entry}` line each: the flow dump of {id: entry} without its outer braces
529
+ lines = "".join(
530
+ yaml.safe_dump(
531
+ {t: theirs[t]}, default_flow_style=True, width=10**6, allow_unicode=True
532
+ ).strip()[1:-1]
533
+ + "\n"
534
+ for t in added
535
+ )
536
+ return [str(t) for t in added], [str(t) for t in kept], lines
537
+
538
+
539
+ @dataclass(frozen=True)
540
+ class _ImportPlan:
541
+ """What an import does: the files it lists, those it copies, finds identical, finds in conflict and skips, the
542
+ notes by kind, and the topics it adds and keeps (with the text it appends to the destination's topics.yaml)."""
543
+
544
+ src: Path
545
+ dest: Path
546
+ files: list[str]
547
+ todo: list[str]
548
+ same: list[str]
549
+ conflicts: list[str]
550
+ skipped: list[str]
551
+ kinds: collections.Counter[str]
552
+ added: list[str]
553
+ kept: list[str]
554
+ topic_text: str
555
+
556
+
557
+ def _import_source(args: argparse.Namespace, dest: Path) -> Path | int:
558
+ """The resolved source folder; 2 after a message on stderr when it is no folder or overlaps the store."""
559
+ src = Path(args.source).expanduser()
560
+ if not src.is_dir():
561
+ print(f"mem: the source is not a folder: {src}", file=sys.stderr)
562
+ return 2
563
+ src = src.resolve()
564
+ if records.inside(src, dest) or records.inside(dest, src):
565
+ print(
566
+ "mem: the source and the store must be separate folders, neither inside the other.",
567
+ file=sys.stderr,
568
+ )
569
+ return 2
570
+ return src
571
+
572
+
573
+ def _import_verdict(src: Path, dest: Path, rel: str, overwrite: bool) -> str:
574
+ """What an import does with one file: `skipped` (a symlink in the store), `same`, `conflict` or `copy`."""
575
+ target = dest / rel
576
+ try:
577
+ safe_io.refuse_symlink_chain(dest, target)
578
+ except safe_io.UnsafePath:
579
+ return "skipped"
580
+ data = (src / rel).read_bytes()
581
+ if target.is_file():
582
+ if target.read_bytes() == data:
583
+ return "same"
584
+ if not overwrite:
585
+ return "conflict"
586
+ return "copy"
587
+
588
+
589
+ def _import_plan(
590
+ args: argparse.Namespace, src: Path, dest: Path, topics: tuple[list[str], list[str], str]
591
+ ) -> _ImportPlan:
592
+ """List the source and sort its files by what an import does with them."""
593
+ skipped: list[str] = []
594
+ if (src / "topics.yaml").is_symlink():
595
+ skipped.append("topics.yaml")
596
+ files = _import_files(src, args.with_sources, args.research_data, skipped)
597
+ groups: dict[str, list[str]] = {"copy": [], "same": [], "conflict": [], "skipped": skipped}
598
+ for rel in files:
599
+ groups[_import_verdict(src, dest, rel, args.overwrite)].append(rel)
600
+ kinds = collections.Counter(k for k in map(_note_kind, files) if k)
601
+ added, kept, topic_text = topics
602
+ return _ImportPlan(
603
+ src,
604
+ dest,
605
+ files,
606
+ groups["copy"],
607
+ groups["same"],
608
+ groups["conflict"],
609
+ skipped,
610
+ kinds,
611
+ added,
612
+ kept,
613
+ topic_text,
614
+ )
615
+
616
+
617
+ def _import_topics_bytes(root: Path, topic_text: str) -> bytes:
618
+ path = root / "topics.yaml"
619
+ safe_io.refuse_symlink_chain(root, path)
620
+ current = path.read_text(encoding="utf-8")
621
+ return (current + ("" if current.endswith("\n") or not current else "\n") + topic_text).encode()
622
+
623
+
624
+ def _import_log_bytes(root: Path, planned: dict[Path, bytes]) -> bytes | None:
625
+ changes = {}
626
+ for path, replacement in planned.items():
627
+ try:
628
+ before = path.read_bytes()
629
+ before.decode("utf-8")
630
+ except (FileNotFoundError, UnicodeDecodeError):
631
+ continue
632
+ changes[path] = (before, common._sha(replacement))
633
+ if not changes:
634
+ return None
635
+ log = root / records.CURATION_LOG
636
+ safe_io.refuse_symlink_chain(root, log)
637
+ current = log.read_bytes() if log.exists() else b""
638
+ if current and not current.endswith(b"\n"):
639
+ current += b"\n"
640
+ return current + common._group_entries(root, changes, "import").encode()
641
+
642
+
643
+ def _import_payloads(plan: _ImportPlan, root: Path, log: bool) -> dict[Path, bytes]:
644
+ planned = {}
645
+ for rel in plan.todo:
646
+ if rel.startswith(".sources/") and not log:
647
+ continue
648
+ target = root / rel
649
+ source = plan.src / rel
650
+ safe_io.refuse_symlink_chain(root, target)
651
+ safe_io.refuse_symlink_chain(plan.src, source)
652
+ planned[target] = source.read_bytes()
653
+ if log and (history := _import_log_bytes(root, planned)) is not None:
654
+ planned[root / records.CURATION_LOG] = history
655
+ if plan.topic_text:
656
+ planned[root / "topics.yaml"] = _import_topics_bytes(root, plan.topic_text)
657
+ return planned
658
+
659
+
660
+ def _import_apply(plan: _ImportPlan, root: Path, log: bool) -> None:
661
+ """Publish rollback data before writing a real import. The index is reconstructible from the store."""
662
+ planned = _import_payloads(plan, root, log)
663
+ if log and planned:
664
+ import_recovery.publish(root, planned)
665
+ for target, replacement in planned.items():
666
+ safe_io.refuse_symlink_chain(root, target)
667
+ target.parent.mkdir(parents=True, exist_ok=True)
668
+ safe_io.replace_file(target, replacement)
669
+ index_files.apply_index(root)
670
+ if log and planned:
671
+ import_recovery.clear(root)
672
+
673
+
674
+ def _import_run(plan: _ImportPlan, dry_run: bool) -> list[note_fields.Problem]:
675
+ """Apply the plan, or a dry run of it on a scratch copy of the store; returns the check problems afterwards."""
676
+ if dry_run:
677
+ with tempfile.TemporaryDirectory() as tmp:
678
+ scratch = Path(tmp) / "store"
679
+ shutil.copytree(plan.dest, scratch, ignore=shutil.ignore_patterns(".*"))
680
+ _import_apply(plan, scratch, False)
681
+ return check_rules.check(scratch)
682
+ _import_apply(plan, plan.dest, True)
683
+ return check_rules.check(plan.dest)
684
+
685
+
686
+ def _import_report(
687
+ plan: _ImportPlan, problems: list[note_fields.Problem], flagged: list[str]
688
+ ) -> None:
689
+ print(f"source: {plan.src}")
690
+ print(f"destination: {plan.dest}")
691
+ print(
692
+ f"notes: {plan.kinds['literature']} literature, {plan.kinds['knowledge']} knowledge, {plan.kinds['research']} research"
693
+ )
694
+ print(
695
+ f"files: {len(plan.todo)} copied, {len(plan.same)} identical, {len(plan.conflicts)} conflicts"
696
+ )
697
+ print(f"topics: {len(plan.added)} added, {len(plan.kept)} kept as they were")
698
+ print(f"check: {len(problems)} problems")
699
+ print(f"flagged: {len(flagged)} files")
700
+ for header, items in (
701
+ ("skipped symlinks:", sorted(plan.skipped)),
702
+ ("conflicts:", plan.conflicts),
703
+ ("topics kept:", plan.kept),
704
+ ("check problems (first 20):", [str(p) for p in problems[:20]]),
705
+ ("flagged:", flagged),
706
+ ):
707
+ if items:
708
+ print(header)
709
+ for item in items:
710
+ print(f" {item}")
711
+
712
+
713
+ def _run_import(args: argparse.Namespace, src: Path, dest: Path) -> int:
714
+ if import_recovery.pending(dest):
715
+ raise OSError("an import was interrupted. Run mem import-recover before retrying")
716
+ plan = _import_plan(args, src, dest, _union_topics(src, dest))
717
+ flagged = _flag_import(src, plan.files)
718
+ problems = _import_run(plan, args.dry_run)
719
+ _import_report(plan, problems, flagged)
720
+ common.log_usage(
721
+ dest, {"cmd": "import", "copied": len(plan.todo), "conflicts": len(plan.conflicts)}
722
+ )
723
+ return 0
724
+
725
+
726
+ def cmd_import(args: argparse.Namespace) -> int:
727
+ dest = args.root.resolve()
728
+ src = _import_source(args, dest)
729
+ if isinstance(src, int):
730
+ return src
731
+ try:
732
+ with contextlib.nullcontext() if args.dry_run else import_recovery.locked(dest):
733
+ return _run_import(args, src, dest)
734
+ except (note_files.FrontmatterError, OSError) as exc:
735
+ print(f"mem: import failed: {exc}", file=sys.stderr)
736
+ return 2
737
+
738
+
739
+ def _recover_import(root: Path) -> bool:
740
+ if not import_recovery.pending(root):
741
+ return False
742
+ import_recovery.rollback(root)
743
+ index_files.apply_index(root)
744
+ import_recovery.clear(root)
745
+ return True
746
+
747
+
748
+ def cmd_import_recover(args: argparse.Namespace) -> int:
749
+ root = args.root.resolve()
750
+ try:
751
+ with import_recovery.locked(root):
752
+ recovered = _recover_import(root)
753
+ except (OSError, TypeError, ValueError, note_files.FrontmatterError) as exc:
754
+ print(f"mem: import recovery failed: {exc}", file=sys.stderr)
755
+ return 2
756
+ print("Interrupted import rolled back." if recovered else "No interrupted import.")
757
+ return 0
758
+
759
+
760
+ def cmd_fetch_sources(args: argparse.Namespace) -> int:
761
+ if args.text_only:
762
+ lines, ok = build_missing_texts(args.root, args.paths)
763
+ else:
764
+ lines, ok = fetch_sources(args.root, args.paths, force=args.force)
765
+ print("\n".join(lines))
766
+ return 0 if ok else 1