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,1282 @@
1
+ """The `new`, `note` (edit and marks), `rename` and `unify` handlers (A5, ADR 0028): the commands that write notes, with `new_note`, the attach-to-section helpers and `_NEW_FIELDS`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import contextlib
7
+ import dataclasses
8
+ import datetime
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import urllib.parse
14
+ import uuid
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any, TypedDict, Unpack, cast
18
+
19
+ import yaml
20
+
21
+ from memory_cli.commands import common
22
+ from memory_cli.core import safe_io
23
+ from memory_cli.memories import records
24
+ from memory_cli.notes import check as check_rules
25
+ from memory_cli.notes import fields as note_fields
26
+ from memory_cli.notes import index as index_files
27
+ from memory_cli.notes import links as link_rules
28
+ from memory_cli.notes import note as note_files
29
+ from memory_cli.notes import search as note_search
30
+ from memory_cli.syntheses import document, units
31
+ from memory_cli.syntheses import edit as synthesis_edit
32
+
33
+ if TYPE_CHECKING:
34
+ import argparse
35
+ from collections.abc import Mapping, Sequence
36
+
37
+ _NOTE_PATH_PARTS = 3 # `<folder>/<domain>/<file>.md`
38
+
39
+
40
+ class NoteFormatError(ValueError):
41
+ """A note file that a command cannot edit as it is."""
42
+
43
+
44
+ def _dump_frontmatter(data: dict) -> str:
45
+ dumped = yaml.safe_dump(
46
+ data, sort_keys=False, allow_unicode=True, default_flow_style=None, width=float("inf")
47
+ )
48
+ return f"---\n{dumped}---\n"
49
+
50
+
51
+ def _knowledge_name_problem(stem: str) -> str | None:
52
+ if word := note_fields.instruction_word(stem):
53
+ return (
54
+ f'knowledge name reads as an instruction ("{word}-..."): {note_fields._INSTRUCTION_FIX}'
55
+ )
56
+ if len(stem) > check_rules.MAX_KNOWLEDGE_NAME:
57
+ return f"knowledge name too long ({len(stem)} characters): {check_rules._LONG_NAME_FIX}"
58
+ return None
59
+
60
+
61
+ def _note_template_and_topics(root: Path, note_type: str) -> tuple[str, dict]:
62
+ """The template body of a note type and the known topics, from the hub."""
63
+ template = root / "templates" / f"{note_type}.md"
64
+ try:
65
+ _, template_body, _ = note_files.split_frontmatter(note_files._read_text(template))
66
+ known = note_files.load_topics(root)
67
+ except note_files.FrontmatterError as exc:
68
+ raise common.NewNoteError(f"cannot read template or topics: {exc}") from exc
69
+ return template_body, known
70
+
71
+
72
+ def _note_domain_and_topics(known: dict, topics: list[str]) -> tuple[str, list[str]]:
73
+ """The root topic (the folder) of the first topic, and every topic with its ancestors."""
74
+ if not topics:
75
+ raise common.NewNoteError("at least one topic is required")
76
+ for t in topics:
77
+ if t not in known:
78
+ raise common.NewNoteError(
79
+ f"unknown topic '{t}': use an id from topics.yaml or add it there"
80
+ )
81
+ domain = note_files.root_of(known, topics[0])
82
+ if domain not in note_files.root_topics(known):
83
+ raise common.NewNoteError(
84
+ f"topic '{topics[0]}' has no root topic (its parent chain ends at "
85
+ f"'{domain}'): fix its parent in topics.yaml"
86
+ )
87
+ all_topics = list(topics)
88
+ for t in topics:
89
+ all_topics += [a for a in note_files.ancestors(known, t) if a not in all_topics]
90
+ return domain, all_topics
91
+
92
+
93
+ def _note_literature_target(
94
+ root: Path, domain: str, slug: str, meta: dict[str, Any], today: datetime.date
95
+ ) -> tuple[Path, str]:
96
+ """Fill the literature fields of `meta`; return the target path and the name to check."""
97
+ author = meta.pop("author", "")
98
+ names = [a.strip() for a in author.split(",") if a.strip()] if isinstance(author, str) else []
99
+ meta["authors"] = names
100
+ first = note_files.slugify(names[0]) if names else ""
101
+ if not first:
102
+ raise common.NewNoteError(
103
+ "author must contain at least one ASCII letter or digit to form the filename"
104
+ )
105
+ if check_rules._starts_with_author(slug.split("-"), first):
106
+ raise common.NewNoteError(
107
+ f"slug '{slug}' repeats the first author '{first}', which the "
108
+ f"filename already holds: drop '{first}-' from --slug"
109
+ )
110
+ if slug.split("-", maxsplit=1)[0] == str(meta.get("year")):
111
+ raise common.NewNoteError(
112
+ f"slug '{slug}' repeats the year; `new` adds '<year>-<author>-' "
113
+ "itself: pass only the descriptive part as --slug"
114
+ )
115
+ name = f"{meta.get('year')}-{first}-{slug}.md"
116
+ meta["added"] = today.isoformat()
117
+ return root / "literature" / domain / name, name
118
+
119
+
120
+ def _note_knowledge_target(
121
+ root: Path, domain: str, slug: str, meta: dict[str, Any], today: datetime.date
122
+ ) -> tuple[Path, str]:
123
+ """Fill the knowledge fields of `meta`; return the target path and the name to check."""
124
+ if problem := _knowledge_name_problem(slug):
125
+ raise common.NewNoteError(problem)
126
+ meta["updated"] = today.isoformat()
127
+ pattern_name = f"{slug}.md"
128
+ return root / "knowledge" / domain / pattern_name, pattern_name
129
+
130
+
131
+ def _note_research_target(
132
+ root: Path, domain: str, slug: str, meta: dict[str, Any], today: datetime.date
133
+ ) -> tuple[Path, str]:
134
+ """Fill the research fields of `meta`; return the target path and the name to check."""
135
+ meta.update(status="idea", started=f"{today:%Y-%m}")
136
+ pattern_name = f"{today:%Y-%m}-{slug}"
137
+ return root / "research" / pattern_name / "README.md", pattern_name
138
+
139
+
140
+ _NOTE_TARGETS = {
141
+ "literature": _note_literature_target,
142
+ "knowledge": _note_knowledge_target,
143
+ }
144
+
145
+
146
+ def _note_ordered_fields(note_type: str, meta: dict[str, Any]) -> dict[str, Any]:
147
+ """`meta` in schema order, every value validated; raises on a missing, invalid or extra field."""
148
+ ordered = {}
149
+ for field, validator in note_fields.SCHEMAS[note_type].items():
150
+ if field not in meta and field in note_fields.OPTIONAL_FIELDS:
151
+ continue
152
+ if field not in meta:
153
+ raise common.NewNoteError(f"missing value for '{field}'")
154
+ if (fix := validator(meta[field])) is not None:
155
+ raise common.NewNoteError(f"invalid value for '{field}': {fix}")
156
+ ordered[field] = meta[field]
157
+ extra = set(meta) - set(ordered)
158
+ if extra:
159
+ raise common.NewNoteError(f"unexpected fields for {note_type}: {', '.join(sorted(extra))}")
160
+ return ordered
161
+
162
+
163
+ def _note_refuse_existing(root: Path, note_type: str, target: Path) -> None:
164
+ if note_type == "research" and target.parent.exists():
165
+ raise common.NewNoteError(
166
+ f"folder {target.parent.relative_to(root).as_posix()} already exists: "
167
+ "choose another slug"
168
+ )
169
+ if target.exists():
170
+ raise common.NewNoteError(f"{target.relative_to(root).as_posix()} already exists")
171
+
172
+
173
+ def new_note(
174
+ root: Path,
175
+ note_type: str,
176
+ *,
177
+ slug: str,
178
+ topics: list[str],
179
+ today: datetime.date,
180
+ **fields: Any,
181
+ ) -> Path:
182
+ """Create a note from its template (or with the `body` field in place of the template body),
183
+ refusing bad slugs, unknown topics and existing paths."""
184
+ if note_type not in note_fields.SCHEMAS:
185
+ raise common.NewNoteError(f"unknown note type '{note_type}'")
186
+ body = fields.pop("body", None)
187
+ template_body, known = _note_template_and_topics(root, note_type)
188
+ domain, all_topics = _note_domain_and_topics(known, topics)
189
+
190
+ meta: dict[str, Any] = dict(fields)
191
+ plan_target = _NOTE_TARGETS.get(note_type, _note_research_target)
192
+ target, pattern_name = plan_target(root, domain, slug, meta, today)
193
+ meta["topics"] = all_topics
194
+
195
+ if not check_rules.NAME_PATTERNS[note_type].fullmatch(pattern_name):
196
+ raise common.NewNoteError(
197
+ f"invalid name '{pattern_name}': {check_rules._NAME_FIX[note_type]}"
198
+ )
199
+ ordered = _note_ordered_fields(note_type, meta)
200
+ _note_refuse_existing(root, note_type, target)
201
+
202
+ target.parent.mkdir(parents=True, exist_ok=True)
203
+ safe_io.replace_file(
204
+ target,
205
+ (_dump_frontmatter(ordered) + (template_body if body is None else body)).encode("utf-8"),
206
+ )
207
+ try:
208
+ index_files.apply_index(root)
209
+ except note_files.FrontmatterError as exc:
210
+ raise common.NewNoteError(
211
+ f"{target.relative_to(root).as_posix()} was created but the index "
212
+ f"was not updated ({exc}): fix it, then run mem index"
213
+ ) from exc
214
+ return target
215
+
216
+
217
+ def _link_points_at(base: Path, target: str, raw: str, old: Path) -> bool:
218
+ """Whether the link `target` (`raw` is its path part) in the file `base` points at the file `old`."""
219
+ if target.startswith(("#", "mailto:")) or link_rules._SCHEME.match(target) or not raw:
220
+ return False
221
+ try:
222
+ return (base.parent / urllib.parse.unquote(raw)).resolve() == old
223
+ except (OSError, ValueError):
224
+ return False
225
+
226
+
227
+ def _link_edits(
228
+ text: str, base: Path, old: Path, new_name: str, new_path: Path | None = None
229
+ ) -> tuple[str, int]:
230
+ """`text` of the file `base` with each relative link to `old` pointing at `new_name`, and their count.
231
+
232
+ Links are found as `_relative_links` finds them (code is masked in place, so offsets stay valid);
233
+ only the file name of the path part changes: prefix, `#anchor` and link text are kept. With `new_path`
234
+ (resolved, like `old` and `base`) the whole path part is recomputed from `base`'s folder instead, because
235
+ the note may sit in another folder.
236
+ """
237
+ lines = text.split("\n")
238
+ masked = link_rules._CODE_SPAN.sub(
239
+ lambda m: re.sub(r"[^\n]", " ", m.group(0)),
240
+ "\n".join(
241
+ " " * len(l) if f else l
242
+ for l, f in zip(lines, link_rules._in_fence(lines), strict=False)
243
+ ),
244
+ )
245
+ count = 0
246
+ for i, line in enumerate(masked.split("\n")):
247
+ for start, end in reversed(link_rules._target_spans(line, True)):
248
+ target = line[start:end]
249
+ raw = target.split("#", 1)[0]
250
+ hit = _link_points_at(base, target, raw, old)
251
+ if hit and new_path is not None:
252
+ lines[i] = (
253
+ lines[i][:start]
254
+ + Path(os.path.relpath(new_path, base.parent)).as_posix()
255
+ + lines[i][start + len(raw) :]
256
+ )
257
+ count += 1
258
+ elif hit:
259
+ cut = start + len(raw) - len(raw.rsplit("/", 1)[-1])
260
+ lines[i] = lines[i][:cut] + new_name + lines[i][start + len(raw) :]
261
+ count += 1
262
+ return "\n".join(lines), count
263
+
264
+
265
+ def _rename_handle_fields(text: str, old: str, new: str) -> tuple[str, int]:
266
+ """`text` with `superseded_by` and `distinct_from` values that name the note `old` naming `new`, and their count."""
267
+ # `part_of` is not renamed here: it names a synthesis, and `rename` takes only literature and knowledge notes.
268
+ try:
269
+ meta, _, _ = note_files.split_frontmatter(text)
270
+ except note_files.FrontmatterError:
271
+ return text, 0
272
+ count = 0
273
+ if isinstance(meta, dict):
274
+ if meta.get("superseded_by") == old:
275
+ text, count = common._set_field(text, "superseded_by", new), count + 1
276
+ names = meta.get("distinct_from")
277
+ if isinstance(names, list) and old in names:
278
+ text, count = (
279
+ common._set_field(
280
+ text, "distinct_from", sorted(new if h == old else h for h in names)
281
+ ),
282
+ count + 1,
283
+ )
284
+ return text, count
285
+
286
+
287
+ def _rename_source(root: Path, arg: str) -> Path:
288
+ """The literature or knowledge note `arg` names exactly, else a refusal."""
289
+ old = common.resolve_note(root, arg, prefix=False)
290
+ if isinstance(old, list):
291
+ raise common.NewNoteError(
292
+ f"ambiguous: {arg} matches {len(old)} notes: {', '.join(old[:10])}"
293
+ )
294
+ parts = old.relative_to(root).parts if old else ()
295
+ if (
296
+ old is None
297
+ or len(parts) != _NOTE_PATH_PARTS
298
+ or parts[0] not in {"literature", "knowledge"}
299
+ or old.name == "README.md"
300
+ or note_files._is_hidden(old, root)
301
+ ):
302
+ raise common.NewNoteError(
303
+ f"{arg} is not a literature or knowledge note: give its path or exact handle "
304
+ "(no prefix; investigations are not renamed)"
305
+ )
306
+ return old
307
+
308
+
309
+ def _rename_keep_literature_prefix(root: Path, old: Path, stem: str) -> None:
310
+ """Refuse a new literature name that drops the `<year>-<author>-` prefix or repeats it after it."""
311
+ meta = note_files._read_note("literature", old, root).meta
312
+ authors = meta.get("authors") if isinstance(meta, dict) else None
313
+ year, *tokens = old.stem.split("-")
314
+ slug = (
315
+ note_files.slugify(cast("list[str]", authors)[0]) # `_authors` found a valid list
316
+ if note_fields._authors(authors) is None
317
+ else tokens[0]
318
+ ) # as rule_consistency: may span tokens
319
+ n = next((k for k in range(1, len(tokens)) if "".join(tokens[:k]) == slug), 1)
320
+ new_year, *new_tokens = stem.split("-")
321
+ if new_year != year or tokens[:n] != new_tokens[:n]:
322
+ raise common.NewNoteError(f"the name must keep the prefix {'-'.join([year, *tokens[:n]])}-")
323
+ if (rest := new_tokens[n:]) and (
324
+ check_rules._starts_with_author(rest, slug) or rest[0] == year
325
+ ):
326
+ raise common.NewNoteError("the name repeats the author or the year after the prefix")
327
+
328
+
329
+ def _rename_check_name(root: Path, old: Path, kind: str, stem: str) -> None:
330
+ """Refuse a new name that breaks the naming rules of the kind or is taken by another note."""
331
+ name = f"{stem}.md"
332
+ if not check_rules.NAME_PATTERNS[kind].fullmatch(name):
333
+ raise common.NewNoteError(f"invalid name '{name}': {check_rules._NAME_FIX[kind]}")
334
+ if kind == "knowledge" and (problem := _knowledge_name_problem(stem)):
335
+ raise common.NewNoteError(problem)
336
+ if kind == "literature":
337
+ _rename_keep_literature_prefix(root, old, stem)
338
+ if old.with_name(name).exists() or any(
339
+ note_files._handle(p.relative_to(root).as_posix()) == stem
340
+ for _, p in note_files._note_files(root)
341
+ ):
342
+ raise common.NewNoteError(f"a note named '{stem}' already exists")
343
+
344
+
345
+ def _rename_link_edits(root: Path, old: Path, stem: str) -> tuple[dict[Path, str], int]:
346
+ """The new text of every markdown file that links to, or names the handle or copy of, `old`; and the count."""
347
+ edits: dict[Path, str] = {}
348
+ links = 0
349
+ copy = f"{common.SOURCES_DIR}/{old.stem}/"
350
+ for path in link_rules._markdown_files(root):
351
+ try:
352
+ text = note_files._read_text(path)
353
+ except note_files.FrontmatterError as exc:
354
+ raise common.NewNoteError(
355
+ f"cannot read {path.relative_to(root).as_posix()} to rewrite its links ({exc}): "
356
+ "fix it, then rename"
357
+ ) from exc
358
+ edited, count = _link_edits(text, path, old, f"{stem}.md")
359
+ count += edited.count(copy) # a note's text naming its local copy
360
+ edited, named = _rename_handle_fields(edited, old.stem, stem)
361
+ count += named
362
+ if count:
363
+ edits[path], links = (
364
+ edited.replace(copy, f"{common.SOURCES_DIR}/{stem}/"),
365
+ links + count,
366
+ )
367
+ return edits, links
368
+
369
+
370
+ def _rename_refuse_locked(root: Path, paths: list[Path]) -> None:
371
+ locked = [p for p in paths if not os.access(p, os.W_OK)]
372
+ if locked:
373
+ raise common.NewNoteError(
374
+ f"not writable: {', '.join(p.relative_to(root).as_posix() for p in locked)}"
375
+ )
376
+
377
+
378
+ def rename_note(root: Path, arg: str, new_stem: str) -> tuple[Path, int, int]:
379
+ """Rename a literature or knowledge note in its folder; return (new path, links rewritten, files changed).
380
+
381
+ Every edit is computed before anything is written, so a refusal leaves the hub untouched.
382
+ """
383
+ root = root.resolve()
384
+ old = _rename_source(root, arg)
385
+ stem = new_stem.removesuffix(".md")
386
+ new = old.with_name(f"{stem}.md")
387
+ _rename_check_name(root, old, old.relative_to(root).parts[0], stem)
388
+ sources, new_sources = root / common.SOURCES_DIR / old.stem, root / common.SOURCES_DIR / stem
389
+ if new_sources.exists():
390
+ raise common.NewNoteError(f"{common.SOURCES_DIR}/{stem} already exists")
391
+ edits, links = _rename_link_edits(root, old, stem)
392
+ _rename_refuse_locked(
393
+ root, [*edits, old, old.parent, *((sources, sources.parent) if sources.is_dir() else ())]
394
+ )
395
+ originals = {(new if p == old else p): p.read_bytes() for p in (*edits, old)}
396
+ listings = _index_files(root)
397
+ for path, text in edits.items():
398
+ safe_io.replace_file(path, text.encode("utf-8"))
399
+ old.rename(new)
400
+ if sources.is_dir():
401
+ sources.rename(new_sources)
402
+ try:
403
+ index_files.apply_index(root)
404
+ except note_files.FrontmatterError as exc:
405
+ raise common.NewNoteError(
406
+ f"{new.relative_to(root).as_posix()} was renamed but the index was not "
407
+ f"updated ({exc}): fix it, then run mem index"
408
+ ) from exc
409
+ common._log_group(root, _with_changed_listings(originals, listings), "rename", {new: old})
410
+ return new, links, len(edits)
411
+
412
+
413
+ _CONFIDENCE_ORDER = ("low", "medium", "high")
414
+
415
+
416
+ def _index_files(root: Path) -> dict[Path, bytes]:
417
+ """The README listing files that `apply_index` may rewrite, with their bytes now (those that exist)."""
418
+ try:
419
+ targets = index_files.index_targets(
420
+ root, note_files.discover_notes(root), note_files.load_topics(root)
421
+ )
422
+ except note_files.FrontmatterError:
423
+ return {}
424
+ return {t.path: t.path.read_bytes() for t in targets if t.path.is_file()}
425
+
426
+
427
+ def _with_changed_listings(
428
+ originals: dict[Path, bytes], listings: Mapping[Path, bytes]
429
+ ) -> dict[Path, bytes]:
430
+ """`originals` plus each listing file in `listings` whose bytes are not what they were."""
431
+ return {**{p: b for p, b in listings.items() if p.read_bytes() != b}, **originals}
432
+
433
+
434
+ def _resolve_notes(root: Path, args: Sequence[str]) -> list[Path]:
435
+ typed = {p.resolve() for _, p in note_files._note_files(root)}
436
+ found = []
437
+ for arg in args:
438
+ path = common.resolve_note(root, arg)
439
+ if isinstance(path, list):
440
+ raise common.NewNoteError(
441
+ f"ambiguous: {arg} matches {len(path)} notes: {', '.join(path[:10])}"
442
+ )
443
+ if path is None or path not in typed:
444
+ raise common.NewNoteError(f"no note {arg}")
445
+ found.append(path)
446
+ return found
447
+
448
+
449
+ @dataclass(frozen=True)
450
+ class UnifyRequest:
451
+ """What the owner asked `unify_notes` to write: the unified text, whether dropped links are meant, the date."""
452
+
453
+ body: str
454
+ drop: bool
455
+ today: datetime.date
456
+
457
+
458
+ def _unify_readable_notes(root: Path, paths: list[Path]) -> list[note_files.Note]:
459
+ """The parsed notes of `paths`, refusing the same note twice, an unreadable one and mixed types."""
460
+ if len(set(paths)) != len(paths):
461
+ raise common.NewNoteError("the same note is named twice: unify needs different notes")
462
+ notes = [note_files._read_note(p.relative_to(root).parts[0], p, root) for p in paths]
463
+ for note in notes:
464
+ if note.error is not None or not isinstance(note.meta, dict):
465
+ raise common.NewNoteError(
466
+ f"{note.rel} cannot be read ({note.error or 'frontmatter is not a mapping'})"
467
+ )
468
+ if len({n.type for n in notes}) > 1:
469
+ raise common.NewNoteError("the notes are of different types: unify joins notes of one type")
470
+ return notes
471
+
472
+
473
+ def _unify_refuse_superseded(root: Path, notes: list[note_files.Note]) -> None:
474
+ """Refuse a note already superseded, and any note in the store that a note to unify supersedes."""
475
+ for note in notes:
476
+ if note.meta.get("superseded_by") is not None:
477
+ raise common.NewNoteError(
478
+ f"{note.rel} is already superseded by {note.meta['superseded_by']}"
479
+ )
480
+ handles = {note_files._handle(n.rel) for n in notes}
481
+ for note in note_files.discover_notes(root):
482
+ if isinstance(note.meta, dict) and note.meta.get("superseded_by") in handles:
483
+ raise common.NewNoteError(
484
+ f"{note.rel} is already superseded by {note.meta['superseded_by']}: unify into the "
485
+ "note that replaced it, or leave it"
486
+ )
487
+
488
+
489
+ def _unify_refuse_lost_links(
490
+ root: Path, notes: list[note_files.Note], body: str, drop: bool
491
+ ) -> None:
492
+ """Refuse a unified text that drops links of the notes, unless the owner passed `--drop`."""
493
+ unified = {n.rel for n in notes}
494
+ had = set().union(*(note_search._link_targets(root, n) for n in notes))
495
+ lost = sorted(
496
+ had - note_search._link_targets(root, dataclasses.replace(notes[0], body=body)) - unified
497
+ )
498
+ if lost and not drop:
499
+ raise common.NewNoteError(
500
+ f"the unified text drops the links {', '.join(lost)}; use --drop if that is meant."
501
+ )
502
+
503
+
504
+ def _unify_keep_text(notes: list[note_files.Note], request: UnifyRequest) -> str:
505
+ """The text of the kept note: the new body, the union of the topics, the lowest confidence."""
506
+ keep, others = notes[0], notes[1:]
507
+ keep_text = note_files._read_text(keep.path)
508
+ m = common._split_frontmatter_block(keep_text)
509
+ if m is None:
510
+ raise common.NewNoteError(f"{keep.rel} has no frontmatter")
511
+ union = list(keep.meta.get("topics") or [])
512
+ union += [t for o in others for t in (o.meta.get("topics") or []) if t not in union]
513
+ new_text = common._set_field(keep_text[: m.end()] + request.body, "topics", union)
514
+ if "confidence" in note_fields.SCHEMAS[keep.type]:
515
+ ranks = [
516
+ _CONFIDENCE_ORDER.index(n.meta["confidence"])
517
+ for n in notes
518
+ if n.meta.get("confidence") in _CONFIDENCE_ORDER
519
+ ]
520
+ if ranks:
521
+ new_text = common._set_field(new_text, "confidence", _CONFIDENCE_ORDER[min(ranks)])
522
+ if keep.type == "knowledge":
523
+ new_text = common._set_field(new_text, "updated", request.today.isoformat())
524
+ return new_text
525
+
526
+
527
+ def _unify_current_text(root: Path, path: Path, edits: dict[Path, str]) -> str:
528
+ """The text of a file as it stands with the edits so far."""
529
+ original = edits.get(path.resolve())
530
+ if original is not None:
531
+ return original
532
+ try:
533
+ return note_files._read_text(path)
534
+ except note_files.FrontmatterError as exc:
535
+ raise common.NewNoteError(
536
+ f"cannot read {path.relative_to(root).as_posix()} to rewrite its links ({exc}): "
537
+ "fix it, then unify"
538
+ ) from exc
539
+
540
+
541
+ def _unify_rewrite_links(
542
+ root: Path, edits: dict[Path, str], others: list[note_files.Note], keep_path: Path
543
+ ) -> int:
544
+ """Point every link to an other note at the kept note, adding the files to `edits`; the count."""
545
+ links = 0
546
+ skip = {o.path for o in others}
547
+ for path in link_rules._markdown_files(root):
548
+ rel = path.relative_to(root).as_posix()
549
+ if path.resolve() in skip or link_rules._is_index_readme(rel):
550
+ continue
551
+ resolved = path.resolve()
552
+ original = _unify_current_text(root, path, edits)
553
+ text = original
554
+ for o in others:
555
+ text, count = _link_edits(text, resolved, o.path, "", keep_path)
556
+ links += count
557
+ if text != original:
558
+ edits[resolved] = text
559
+ return links
560
+
561
+
562
+ def _unify_write(root: Path, edits: dict[Path, str]) -> None:
563
+ for path in edits: # a note resolved outside the store raises ValueError here, before any write
564
+ path.relative_to(root)
565
+ for path, text in edits.items():
566
+ safe_io.replace_file(path, text.encode("utf-8"))
567
+
568
+
569
+ def _unify_new_problems(
570
+ root: Path, keep_rel: str, before: collections.Counter[tuple[str, str]]
571
+ ) -> list[note_fields.Problem]:
572
+ """The `check` problems the edits introduced; an index that cannot be updated is one."""
573
+ try:
574
+ index_files.apply_index(root)
575
+ after = check_rules.check(root)
576
+ more = (
577
+ collections.Counter((p.path, p.message) for p in after) - before
578
+ ) # counted: a second copy is new
579
+ return [p for p in after if (p.path, p.message) in more]
580
+ except note_files.FrontmatterError as exc:
581
+ return [note_fields.Problem(keep_rel, 1, f"the index was not updated ({exc})")]
582
+
583
+
584
+ def _unify_undo_on_problems(
585
+ root: Path, originals: dict[Path, bytes], problems: list[note_fields.Problem]
586
+ ) -> None:
587
+ """With problems, put every file back and raise them; with none, do nothing."""
588
+ if not problems:
589
+ return
590
+ for path, data in originals.items():
591
+ safe_io.replace_file(path, data)
592
+ with contextlib.suppress(note_files.FrontmatterError, OSError):
593
+ index_files.apply_index(root)
594
+ raise common.NewNoteError(
595
+ f"the unified notes have {len(problems)} problems, so nothing was written:\n"
596
+ + "\n".join(str(p) for p in problems)
597
+ )
598
+
599
+
600
+ def unify_notes(
601
+ root: Path, keep_arg: str, other_args: Sequence[str], request: UnifyRequest
602
+ ) -> tuple[Path, int, int]:
603
+ """Make `keep_arg` the unified note of itself and `other_args`; return (keep path, notes unified, links rewritten).
604
+
605
+ The kept note takes the request's body, the union of the topics and the lowest confidence; each other note
606
+ gets `superseded_by` and stays as a file; every link to an other note in the store points at the kept note.
607
+ The result must pass `check`, else every file is put back and the problems are raised."""
608
+ root = root.resolve()
609
+ notes = _unify_readable_notes(root, _resolve_notes(root, [keep_arg, *other_args]))
610
+ keep, others = notes[0], notes[1:]
611
+ _unify_refuse_superseded(root, notes)
612
+ _unify_refuse_lost_links(root, notes, request.body, request.drop)
613
+
614
+ edits: dict[Path, str] = {keep.path: _unify_keep_text(notes, request)}
615
+ for o in others:
616
+ edits[o.path] = common._set_field(
617
+ note_files._read_text(o.path), "superseded_by", note_files._handle(keep.rel)
618
+ )
619
+ links = _unify_rewrite_links(root, edits, others, keep.path)
620
+ _rename_refuse_locked(root, list(edits))
621
+
622
+ # Line numbers move with the edit, so a problem is known by its file and message: the store may hold
623
+ # problems older than this change (an imported note that links a document left behind), and they do not block it.
624
+ before = collections.Counter((p.path, p.message) for p in check_rules.check(root))
625
+ originals = {p: p.read_bytes() for p in edits}
626
+ listings = _index_files(root)
627
+ _unify_write(root, edits)
628
+ _unify_undo_on_problems(root, originals, _unify_new_problems(root, keep.rel, before))
629
+ common._log_group(root, _with_changed_listings(originals, listings), "unify")
630
+ return keep.path, len(notes), links
631
+
632
+
633
+ SIMILAR_LIMIT = 3
634
+
635
+
636
+ def _own_topics(known: dict, topics: Sequence[str]) -> list[str]:
637
+ """The topics a note was filed under: those that are not the ancestor of another listed topic."""
638
+ return [
639
+ t for t in topics if not any(t in note_files.ancestors(known, o) for o in topics if o != t)
640
+ ]
641
+
642
+
643
+ def _covering(root: Path, topics: Sequence[str]) -> list[document.Synthesis]:
644
+ """Syntheses that list one of `topics` by its exact id (no ancestors, no descendants)."""
645
+ try:
646
+ known = note_files.load_topics(root)
647
+ except note_files.FrontmatterError:
648
+ known = {}
649
+ own = set(_own_topics(known, topics))
650
+ return [
651
+ x
652
+ for x in document.load(root / document.SYNTHESES_DIR)
653
+ if x.error is None and own & set(x.topics)
654
+ ]
655
+
656
+
657
+ def _log_note(root: Path, path: Path, rel: str, action: str) -> None:
658
+ """The note's current text, appended to the store's `.curation-log` before a curation action changes it."""
659
+ entry = {
660
+ "t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
661
+ "action": action,
662
+ "handle": rel,
663
+ "before": path.read_bytes().decode("utf-8"),
664
+ }
665
+ safe_io.append_text(root / records.CURATION_LOG, json.dumps(entry, ensure_ascii=False) + "\n")
666
+
667
+
668
+ def _set_part_of(text: str, part_of: str, digest: str) -> str:
669
+ m = re.match(r"---\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|$)", text, re.DOTALL)
670
+ if m is None:
671
+ raise ValueError("the note has no frontmatter")
672
+ kept = [ln for ln in m.group(1).split("\n") if not re.match(r"part_of(_hash)?:", ln)]
673
+ head = (
674
+ "---\n"
675
+ + "\n".join([
676
+ *kept,
677
+ f"part_of: {json.dumps(part_of)}",
678
+ f"part_of_hash: {json.dumps(digest)}",
679
+ ])
680
+ + "\n---\n"
681
+ )
682
+ return head + text[m.end() :]
683
+
684
+
685
+ def _attach(args: argparse.Namespace) -> int:
686
+ root = args.root
687
+ found = common.resolve_note(root, args.note)
688
+ if isinstance(found, list):
689
+ common._ambiguous(args.note, found)
690
+ return 2
691
+ if found is None:
692
+ print(f"mem: no note {args.note}", file=sys.stderr)
693
+ return 2
694
+ rel = found.relative_to(root.resolve()).as_posix()
695
+ if not rel.startswith("knowledge/"):
696
+ print(
697
+ f"mem: {rel} is not a knowledge note: only knowledge notes are part of a synthesis",
698
+ file=sys.stderr,
699
+ )
700
+ return 2
701
+ try:
702
+ syn, sec = common._section_ref(root, args.target)
703
+ text = note_files._read_text(found)
704
+ _log_note(root, found, rel, "attach")
705
+ safe_io.replace_file(
706
+ found,
707
+ _set_part_of(
708
+ text,
709
+ f"{syn.handle}#{sec.handle}",
710
+ units.note_fingerprint(sec.text, common._note_target(rel)),
711
+ ).encode("utf-8"),
712
+ )
713
+ except (ValueError, OSError, note_files.FrontmatterError) as exc:
714
+ print(f"mem: {exc}", file=sys.stderr)
715
+ return 2
716
+ print(f"{note_files._handle(rel)}\tpart of s:{syn.handle}#{sec.handle}")
717
+ common.log_usage(root, {"cmd": "synthesis", "action": "attach"})
718
+ return 0
719
+
720
+
721
+ def _lf(text: str, rel: str) -> str:
722
+ if "\r" in text:
723
+ raise ValueError(f"{rel} has CRLF line ends: convert it to LF first")
724
+ return text
725
+
726
+
727
+ @dataclass(frozen=True)
728
+ class _NoteWritten:
729
+ """A note `mem new` wrote and the text it was given (None when the command gave none)."""
730
+
731
+ path: Path
732
+ body: str | None
733
+
734
+
735
+ def _new_link_part(args: argparse.Namespace, fields: dict[str, Any]) -> str | None:
736
+ """With `--part-of`, add the link to the section it names to `fields`; returns that section's text."""
737
+ if not getattr(args, "part_of", None):
738
+ return None
739
+ syn, sec = common._section_ref(args.root, args.part_of)
740
+ fields["part_of"] = f"{syn.handle}#{sec.handle}"
741
+ fields["part_of_hash"] = units.fingerprint(sec.text)
742
+ return sec.text
743
+
744
+
745
+ def _new_write(
746
+ args: argparse.Namespace, fields: dict[str, Any], topics: list[str]
747
+ ) -> int | _NoteWritten:
748
+ """Write the note after the secret and term checks; the exit code of a refusal instead. `fields` gains the
749
+ `--part-of` link."""
750
+ body = common._read_body(args.body_file) if args.body_file else None
751
+ if common._refuse_secret([*(v for v in fields.values() if isinstance(v, str)), body or ""]):
752
+ return 4
753
+ texts = [
754
+ str(fields[k])
755
+ for k in ("title", "claim", "url", "question", "author", "slug")
756
+ if k in fields
757
+ ]
758
+ if refused := common._check_terms(
759
+ [*texts, args.slug, body or ""], "note", getattr(args, "owner_approved", False)
760
+ ):
761
+ return refused
762
+ part_text = _new_link_part(args, fields) # the text of the section `--part-of` names
763
+ path = new_note(
764
+ args.root,
765
+ args.type,
766
+ slug=args.slug,
767
+ topics=topics,
768
+ today=datetime.date.today(),
769
+ body=body,
770
+ **fields,
771
+ )
772
+ if part_text is not None:
773
+ stamp = units.note_fingerprint(
774
+ part_text, common._note_target(path.relative_to(args.root).as_posix())
775
+ )
776
+ if stamp != fields["part_of_hash"]:
777
+ safe_io.replace_file(
778
+ path,
779
+ common._set_field(note_files._read_text(path), "part_of_hash", stamp).encode(
780
+ "utf-8"
781
+ ),
782
+ )
783
+ return _NoteWritten(path, body)
784
+
785
+
786
+ def _new_covering_hint(args: argparse.Namespace, fields: dict[str, Any], topics: list[str]) -> None:
787
+ """Name the syntheses that cover the topics of a knowledge note that is part of none."""
788
+ if args.type != "knowledge" or "part_of" in fields:
789
+ return
790
+ for syn in _covering(args.root, topics):
791
+ print(
792
+ f"mem: s:{syn.handle} ({syn.title}) covers this topic; a curation pass can attach this note to it "
793
+ "(mem curate --notes).",
794
+ file=sys.stderr,
795
+ )
796
+
797
+
798
+ def _new_check_hint(root: Path, rel: str, body: str | None) -> None:
799
+ """List the check problems of the new note when the command gave it a text."""
800
+ if body is not None and (found := [p for p in check_rules.check(root) if p.path == rel]):
801
+ print(f"check: {len(found)} problems in {rel}:", file=sys.stderr)
802
+ for problem in found:
803
+ print(problem, file=sys.stderr)
804
+
805
+
806
+ def _new_similar_hint(args: argparse.Namespace, fields: dict[str, Any], rel: str) -> None:
807
+ """List the notes that look like the new one."""
808
+ query = fields.get("claim") or fields.get("title") if args.type != "research" else None
809
+ if not (query and records.tokenize(query)):
810
+ return
811
+ try:
812
+ similar = [
813
+ r for r in note_search.search(args.root, query, limit=SIMILAR_LIMIT + 1) if r[0] != rel
814
+ ]
815
+ except (note_files.FrontmatterError, OSError): # the note exists; the hint is optional
816
+ similar = []
817
+ if similar:
818
+ print(
819
+ "Similar notes exist: link them, or edit the existing note if it states the same claim.",
820
+ file=sys.stderr,
821
+ )
822
+ for other, score, title in similar[:SIMILAR_LIMIT]:
823
+ print(f"similar: {other}\t{score:.2f}\t{title}", file=sys.stderr)
824
+
825
+
826
+ def _new_research_hint(args: argparse.Namespace, rel: str) -> None:
827
+ """Say that an investigation with its own material lives on a branch."""
828
+ if args.type != "research":
829
+ return
830
+ branch = f"research/{Path(rel).parent.name}"
831
+ print(
832
+ f"An investigation with its own material lives on a branch (ADR 0006): before committing, "
833
+ f"git switch -c {branch} (uncommitted files move with you); add literature and knowledge "
834
+ "notes on main, then merge main into it.",
835
+ file=sys.stderr,
836
+ )
837
+
838
+
839
+ def _new_report(
840
+ args: argparse.Namespace, fields: dict[str, Any], topics: list[str], written: _NoteWritten
841
+ ) -> None:
842
+ """The new note's path, then the hints about syntheses, check problems, similar notes and branches."""
843
+ rel = written.path.relative_to(args.root).as_posix()
844
+ print(rel)
845
+ _new_covering_hint(args, fields, topics)
846
+ _new_check_hint(args.root, rel, written.body)
847
+ _new_similar_hint(args, fields, rel)
848
+ _new_research_hint(args, rel)
849
+
850
+
851
+ def cmd_new(args: argparse.Namespace) -> int:
852
+ fields = {k: getattr(args, k) for k in _NEW_FIELDS[args.type]}
853
+ topics = [t.strip() for t in args.topics.split(",") if t.strip()]
854
+ try:
855
+ written = _new_write(args, fields, topics)
856
+ except (common.NewNoteError, OSError, ValueError) as exc:
857
+ print(f"mem: {exc}", file=sys.stderr)
858
+ return 1
859
+ if isinstance(written, int):
860
+ return written
861
+ _new_report(args, fields, topics, written)
862
+ return 0
863
+
864
+
865
+ def cmd_unify(args: argparse.Namespace) -> int:
866
+ try:
867
+ body = common._read_body(args.body_file)
868
+ if common._refuse_secret([body]):
869
+ return 4
870
+ if refused := common._check_terms([body], "note", getattr(args, "owner_approved", False)):
871
+ return refused
872
+ keep, count, links = unify_notes(
873
+ args.root,
874
+ args.keep,
875
+ args.others,
876
+ UnifyRequest(body, args.drop, datetime.date.today()),
877
+ )
878
+ except (common.NewNoteError, OSError, ValueError, note_files.FrontmatterError) as exc:
879
+ print(f"mem: {exc}", file=sys.stderr)
880
+ return 1
881
+ print(
882
+ f"{note_files._handle(keep.relative_to(args.root.resolve()).as_posix())}\tunified from {count} notes, {links} links rewritten"
883
+ )
884
+ common.log_usage(args.root, {"cmd": "unify", "notes": count, "links": links, "drop": args.drop})
885
+ return 0
886
+
887
+
888
+ def cmd_rename(args: argparse.Namespace) -> int:
889
+ try:
890
+ path, links, files = rename_note(args.root, args.note, args.new_stem)
891
+ except (common.NewNoteError, OSError) as exc:
892
+ print(f"mem: {exc}", file=sys.stderr)
893
+ return 1
894
+ print(path.relative_to(args.root.resolve()).as_posix())
895
+ print(f"rewrote {links} links in {files} files", file=sys.stderr)
896
+ return 0
897
+
898
+
899
+ def _section_span(text: str, heading: str) -> tuple[list[str], int, int]:
900
+ """The note's lines and the index of the `## heading` line and of the line that ends its text."""
901
+ lines, heads = document._scan(text)
902
+ want = " ".join(heading.removeprefix("## ").split())
903
+ hits = [k for k, (_, h) in enumerate(heads) if " ".join(h.split()) == want]
904
+ if not hits:
905
+ raise ValueError(f"no section '## {want}' in the note")
906
+ if len(hits) > 1:
907
+ raise ValueError(f"the heading '## {want}' is repeated in the note: edit it by hand")
908
+ k = hits[0]
909
+ return lines, heads[k][0], heads[k + 1][0] if k + 1 < len(heads) else len(lines)
910
+
911
+
912
+ class _NoteEditOptions(TypedDict):
913
+ """The keyword part of `_edited_note_text`: what to replace and whether a shrinking edit is allowed."""
914
+
915
+ section: str | None
916
+ body: str | None
917
+ claim: str | None
918
+ topics: list[str] | None
919
+ shrink: bool
920
+ today: datetime.date
921
+
922
+
923
+ def _note_replace_section(text: str, section: str, body: str | None, shrink: bool) -> str:
924
+ """The note's text with the text of the `## section` replaced; ValueError when it is empty or shrinks."""
925
+ lines, head, end = _section_span(text, section)
926
+ new = synthesis_edit._clean(body or "")
927
+ if not new:
928
+ raise ValueError("the section text is empty")
929
+ synthesis_edit._check_body(new)
930
+ if not shrink:
931
+ synthesis_edit._guard_shrink("\n".join(lines[head + 1 : end]).strip("\n"), new)
932
+ lines[head + 1 : end] = ["", *new.split("\n"), ""]
933
+ return "\n".join(lines)
934
+
935
+
936
+ def _note_replace_claim(text: str, meta: dict, claim: str, shrink: bool) -> str:
937
+ """The note's text with its claim replaced; ValueError when the note has none, the new one is empty or shrinks."""
938
+ if not isinstance(meta.get("claim"), str):
939
+ raise NoteFormatError("the note has no claim: only a knowledge note does")
940
+ if not claim:
941
+ raise ValueError("the claim is empty")
942
+ if not shrink:
943
+ synthesis_edit._guard_shrink(meta["claim"], claim, sentences=False)
944
+ return common._set_field(text, "claim", claim)
945
+
946
+
947
+ def _note_require_topic(topic: str, topics: list[str], known: dict, path: Path) -> None:
948
+ """ValueError unless the topic exists, belongs to the domain of the note's folder and comes with its ancestors."""
949
+ if topic not in known:
950
+ raise ValueError(f"unknown topic '{topic}': use an id from topics.yaml")
951
+ domain = path.parent.name
952
+ if (
953
+ path.parent.parent.name in {"literature", "knowledge"}
954
+ and note_files.root_of(known, topic) != domain
955
+ ):
956
+ raise ValueError(
957
+ f"topic '{topic}' belongs to the domain {note_files.root_of(known, topic)}, not to {domain}, "
958
+ "where the note lives"
959
+ )
960
+ if missing := [a for a in note_files.ancestors(known, topic) if a not in topics]:
961
+ raise ValueError(f"topic '{topic}' needs its ancestor '{missing[0]}' in the list too")
962
+
963
+
964
+ def _note_replace_topics(text: str, path: Path, topics: list[str], known: dict) -> str:
965
+ """The note's text with its topics replaced; ValueError when the list is empty or a topic is refused."""
966
+ if not topics:
967
+ raise ValueError("at least one topic is required")
968
+ for t in topics:
969
+ _note_require_topic(t, topics, known, path)
970
+ return common._set_field(text, "topics", topics)
971
+
972
+
973
+ def _edited_note_text(
974
+ text: str, path: Path, meta: dict, known: dict, **options: Unpack[_NoteEditOptions]
975
+ ) -> tuple[str, list[str]]:
976
+ """The note's text with the section text, the claim and the topics replaced (every other byte stays), and what
977
+ changed; ValueError when a change is refused."""
978
+ what = []
979
+ section, claim, topics = options["section"], options["claim"], options["topics"]
980
+ if section is not None:
981
+ text = _note_replace_section(text, section, options["body"], options["shrink"])
982
+ what.append("section " + " ".join(section.removeprefix("## ").split()))
983
+ if claim is not None:
984
+ text = _note_replace_claim(text, meta, claim, options["shrink"])
985
+ what.append("claim")
986
+ if topics is not None:
987
+ text = _note_replace_topics(text, path, topics, known)
988
+ what.append("topics")
989
+ if "updated" in meta:
990
+ text = common._set_field(text, "updated", options["today"].isoformat())
991
+ return text, what
992
+
993
+
994
+ @dataclass(frozen=True)
995
+ class _NoteSnapshot:
996
+ """A note as it was read: its file, hub-relative path, bytes, text and frontmatter mapping."""
997
+
998
+ found: Path
999
+ rel: str
1000
+ original: bytes
1001
+ text: str
1002
+ meta: dict
1003
+
1004
+
1005
+ def _note_snapshot(root: Path, found: Path) -> _NoteSnapshot:
1006
+ """Read the note; ValueError when it has CRLF line ends, NoteFormatError when its frontmatter is no mapping."""
1007
+ rel = found.relative_to(root).as_posix()
1008
+ original = found.read_bytes()
1009
+ text = _lf(original.decode("utf-8"), rel)
1010
+ meta = note_files.split_frontmatter(text)[0]
1011
+ if not isinstance(meta, dict):
1012
+ raise NoteFormatError(f"{rel} has no frontmatter mapping")
1013
+ return _NoteSnapshot(found, rel, original, text, meta)
1014
+
1015
+
1016
+ def _note_locate(root: Path, name: str) -> Path | int:
1017
+ """The note file `name` names; 2 after listing the candidates when it is ambiguous, ValueError when it is none."""
1018
+ found = common.resolve_note(root, name)
1019
+ if isinstance(found, list):
1020
+ common._ambiguous(name, found)
1021
+ return 2
1022
+ if found is None or found not in {p.resolve() for _, p in note_files._note_files(root)}:
1023
+ raise ValueError(f"no note {name}")
1024
+ return found
1025
+
1026
+
1027
+ @dataclass(frozen=True)
1028
+ class _NoteEditBackup:
1029
+ """What a note edit needs to put things back: the listings' bytes, the curation log and its bytes (None when
1030
+ it did not exist)."""
1031
+
1032
+ listings: dict[Path, bytes]
1033
+ log: Path
1034
+ log_before: bytes | None
1035
+
1036
+
1037
+ def _note_edit_backup(root: Path) -> _NoteEditBackup:
1038
+ log = root / records.CURATION_LOG
1039
+ return _NoteEditBackup(_index_files(root), log, log.read_bytes() if log.exists() else None)
1040
+
1041
+
1042
+ def _note_edit_rollback(snap: _NoteSnapshot, backup: _NoteEditBackup, swapped: bool) -> None:
1043
+ """Put the note (when it was swapped), the listings and the log back as they were."""
1044
+ if swapped:
1045
+ common._swap_file(snap.found, snap.original)
1046
+ for path, data in backup.listings.items():
1047
+ if path.read_bytes() != data:
1048
+ common._swap_file(path, data)
1049
+ if backup.log_before is None:
1050
+ backup.log.unlink(missing_ok=True)
1051
+ else:
1052
+ safe_io.replace_file(backup.log, backup.log_before)
1053
+
1054
+
1055
+ def _commit_note_edit(root: Path, snap: _NoteSnapshot, new: str) -> None:
1056
+ """Write `new` over the note through the undo log; any failure leaves the note, the listings and the log as
1057
+ they were (`mem restore` undoes it)."""
1058
+ group = uuid.uuid4().hex
1059
+ backup = _note_edit_backup(root)
1060
+ entry = {
1061
+ "t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
1062
+ "action": "note-edit",
1063
+ "handle": snap.rel,
1064
+ "group": group,
1065
+ "before": snap.text,
1066
+ "after": common._sha(new.encode("utf-8")),
1067
+ }
1068
+ safe_io.append_text(backup.log, json.dumps(entry, ensure_ascii=False) + "\n")
1069
+ swapped = False
1070
+ try:
1071
+ if snap.found.read_bytes() != snap.original:
1072
+ raise ValueError(
1073
+ f"{snap.rel} changed since it was read, so nothing was written: run the command again"
1074
+ )
1075
+ common._swap_file(snap.found, new.encode("utf-8"))
1076
+ swapped = True
1077
+ index_files.apply_index(root)
1078
+ except BaseException: # any failure leaves the note, the listings and the log as they were
1079
+ _note_edit_rollback(snap, backup, swapped)
1080
+ raise
1081
+ common._log_group(root, _with_changed_listings({}, backup.listings), "note-edit", group=group)
1082
+
1083
+
1084
+ def _note_edit_options(args: argparse.Namespace) -> tuple[str | None, list[str] | None]:
1085
+ """The claim and the topics of `note edit`, normalized; the parser's error when the options do not fit."""
1086
+ if args.section is None and args.claim is None and args.topics is None:
1087
+ raise common.UsageError("note edit needs --section, --claim or --topics")
1088
+ if (args.section is None) != (args.body_file is None):
1089
+ raise common.UsageError("--section and --body-file go together")
1090
+ claim = " ".join(args.claim.split()) if args.claim is not None else None
1091
+ topics = (
1092
+ list(dict.fromkeys(t.strip() for t in args.topics.split(",") if t.strip()))
1093
+ if args.topics is not None
1094
+ else None
1095
+ )
1096
+ return claim, topics
1097
+
1098
+
1099
+ def _note_edit(
1100
+ args: argparse.Namespace, root: Path, claim: str | None, topics: list[str] | None
1101
+ ) -> int | tuple[str, list[str]]:
1102
+ """Edit the note; (its hub-relative path, what changed), or the exit code of a refusal."""
1103
+ body = common._read_body(args.body_file) if args.body_file else None
1104
+ texts = [args.section or "", body or "", claim or "", *(topics or [])]
1105
+ if common._refuse_secret(texts):
1106
+ return 4
1107
+ if refused := common._check_terms(texts, "note", getattr(args, "owner_approved", False)):
1108
+ return refused
1109
+ found = _note_locate(root, args.note)
1110
+ if isinstance(found, int):
1111
+ return found
1112
+ snap = _note_snapshot(root, found)
1113
+ new, what = _edited_note_text(
1114
+ snap.text,
1115
+ found,
1116
+ snap.meta,
1117
+ note_files.load_topics(root),
1118
+ section=args.section,
1119
+ body=body,
1120
+ claim=claim,
1121
+ topics=topics,
1122
+ shrink=args.shrink,
1123
+ today=datetime.date.today(),
1124
+ )
1125
+ _commit_note_edit(root, snap, new)
1126
+ return snap.rel, what
1127
+
1128
+
1129
+ def cmd_note(args: argparse.Namespace) -> int:
1130
+ root = args.root.resolve()
1131
+ claim, topics = _note_edit_options(args)
1132
+ try:
1133
+ edited = _note_edit(args, root, claim, topics)
1134
+ except (
1135
+ common.NewNoteError,
1136
+ OSError,
1137
+ ValueError,
1138
+ note_files.FrontmatterError,
1139
+ yaml.YAMLError,
1140
+ ) as exc:
1141
+ print(f"mem: {exc}", file=sys.stderr)
1142
+ return 2
1143
+ if isinstance(edited, int):
1144
+ return edited
1145
+ rel, what = edited
1146
+ print(f"{note_files._handle(rel)}\tedited {', '.join(what)}")
1147
+ common.log_usage(root, {"cmd": "note", "action": "edit"})
1148
+ return 0
1149
+
1150
+
1151
+ def _source_mark(fact: str, source: str, quote: str) -> tuple[str, str, str]:
1152
+ """The texts of a confirm or dispute, whitespace collapsed; ValueError when one is empty or the source is no URL."""
1153
+ fact, quote, source = (" ".join(t.split()) for t in (fact, quote, source))
1154
+ if not fact or not quote:
1155
+ raise ValueError("the fact and the quote must not be empty")
1156
+ parts = urllib.parse.urlsplit(source)
1157
+ if (
1158
+ parts.scheme not in {"http", "https"}
1159
+ or not parts.netloc
1160
+ or note_fields._url(source) is not None
1161
+ ):
1162
+ raise ValueError("the source must be an http(s) URL")
1163
+ return fact, source, quote
1164
+
1165
+
1166
+ def _evidence_line(text: str, line: str) -> str:
1167
+ """`text` with `line` appended to its `## Evidence` section (added at the end when the note has none)."""
1168
+ if not re.search(r"^## Evidence[ \t]*$", text, re.MULTILINE):
1169
+ return text.rstrip("\n") + f"\n\n## Evidence\n\n{line}\n"
1170
+ lines, head, end = _section_span(text, "Evidence")
1171
+ last = max((i for i in range(head + 1, end) if lines[i].strip()), default=head)
1172
+ lines.insert(last + 1, line)
1173
+ if last == head:
1174
+ lines.insert(last + 1, "")
1175
+ return "\n".join(lines)
1176
+
1177
+
1178
+ def _note_mark_require_options(args: argparse.Namespace, clear: bool) -> None:
1179
+ """The parser's error when the options of `note confirm | dispute` do not fit."""
1180
+ given = [args.fact, args.source, args.quote]
1181
+ if clear and any(v is not None for v in given):
1182
+ raise common.UsageError("--clear goes alone")
1183
+ if not clear and any(v is None for v in given):
1184
+ raise common.UsageError(
1185
+ f"note {args.note_command} needs --fact, --source and --quote"
1186
+ + (" (or --clear)" if args.note_command == "dispute" else "")
1187
+ )
1188
+
1189
+
1190
+ def _note_mark_refused(marks: tuple[str, str, str], approved: bool) -> int:
1191
+ """0 when the texts may be written, else the exit code after a message on stderr."""
1192
+ if common._refuse_secret(list(marks)):
1193
+ return 4
1194
+ return common._check_terms(list(marks), "note", approved)
1195
+
1196
+
1197
+ def _note_require_knowledge(root: Path, found: Path) -> None:
1198
+ """ValueError unless the note is a knowledge note."""
1199
+ rel = found.relative_to(root).as_posix()
1200
+ if not rel.startswith("knowledge/"):
1201
+ raise ValueError(
1202
+ f"{rel} is not a knowledge note: only a knowledge note carries evidence and can be disputed"
1203
+ )
1204
+
1205
+
1206
+ def _note_mark_text(
1207
+ snap: _NoteSnapshot, action: str, clear: bool, marks: tuple[str, str, str], today: str
1208
+ ) -> str:
1209
+ """The note's text with the evidence line of a confirm, the dispute of a dispute, or no dispute for `--clear`."""
1210
+ fact, source, quote = marks
1211
+ if action == "confirm":
1212
+ host = urllib.parse.urlsplit(source).netloc
1213
+ return _evidence_line(
1214
+ snap.text, f'- {today} confirmed: {fact} "{quote}" ([{host}]({source}))'
1215
+ )
1216
+ if clear:
1217
+ if not snap.meta.get("disputed"):
1218
+ raise ValueError(f"{snap.rel} is not disputed")
1219
+ return common._set_field(snap.text, "disputed", None)
1220
+ entry = {"date": today, "fact": fact, "source": source, "quote": quote}
1221
+ disputed = snap.meta.get("disputed")
1222
+ return common._set_field(
1223
+ snap.text, "disputed", [*(disputed if isinstance(disputed, list) else []), entry]
1224
+ )
1225
+
1226
+
1227
+ def _note_mark_edit(args: argparse.Namespace, root: Path, clear: bool) -> int | str:
1228
+ """Write the verdict; the note's hub-relative path, or the exit code of a refusal."""
1229
+ marks = ("", "", "") # not read with `--clear`
1230
+ if not clear:
1231
+ marks = _source_mark(args.fact, args.source, args.quote)
1232
+ if refused := _note_mark_refused(marks, args.owner_approved):
1233
+ return refused
1234
+ found = _note_locate(root, args.note)
1235
+ if isinstance(found, int):
1236
+ return found
1237
+ _note_require_knowledge(root, found)
1238
+ snap = _note_snapshot(root, found)
1239
+ today = datetime.date.today().isoformat()
1240
+ new = _note_mark_text(snap, args.note_command, clear, marks, today)
1241
+ if "updated" in snap.meta:
1242
+ new = common._set_field(new, "updated", today)
1243
+ _commit_note_edit(root, snap, new)
1244
+ return snap.rel
1245
+
1246
+
1247
+ def _note_mark_verdict(action: str, clear: bool) -> str:
1248
+ """The past tense of the command, as the output line words it."""
1249
+ if clear:
1250
+ return "cleared the dispute"
1251
+ return action + ("ed" if action == "confirm" else "d")
1252
+
1253
+
1254
+ def cmd_note_mark(args: argparse.Namespace) -> int:
1255
+ """`mem note confirm|dispute`: a source's verdict on a knowledge note, through the `note edit` write path."""
1256
+ root = args.root.resolve()
1257
+ action = args.note_command
1258
+ clear = action == "dispute" and args.clear
1259
+ _note_mark_require_options(args, clear)
1260
+ try:
1261
+ marked = _note_mark_edit(args, root, clear)
1262
+ except (
1263
+ common.NewNoteError,
1264
+ OSError,
1265
+ ValueError,
1266
+ note_files.FrontmatterError,
1267
+ yaml.YAMLError,
1268
+ ) as exc:
1269
+ print(f"mem: {exc}", file=sys.stderr)
1270
+ return 2
1271
+ if isinstance(marked, int):
1272
+ return marked
1273
+ print(f"{note_files._handle(marked)}\t{_note_mark_verdict(action, clear)}")
1274
+ common.log_usage(root, {"cmd": "note", "action": action})
1275
+ return 0
1276
+
1277
+
1278
+ _NEW_FIELDS = {
1279
+ "literature": ("title", "author", "year", "kind", "level", "url"),
1280
+ "knowledge": ("claim", "confidence", "level", "origin"),
1281
+ "research": ("title", "question"),
1282
+ }