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,581 @@
1
+ """The writes of a synthesis: one section is added, replaced, renamed or removed at a time, and every other byte stays.
2
+
3
+ `edit_section` and its siblings return the new text and the log line; the guards refuse a rewrite that drops too much
4
+ or changes the sources. Imports nothing from mem.py.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import TYPE_CHECKING, TypedDict
11
+
12
+ import yaml
13
+
14
+ from memory_cli.core import safe_io
15
+ from memory_cli.core.yaml_load import safe_load
16
+ from memory_cli.memories import journal
17
+ from memory_cli.memories.matching import STOPWORDS
18
+ from memory_cli.syntheses.document import (
19
+ _FRONTMATTER,
20
+ _HANDLE,
21
+ SUMMARY,
22
+ _links,
23
+ _read,
24
+ _resolved,
25
+ _scan,
26
+ _sources_line,
27
+ _write,
28
+ load_one,
29
+ section_handle,
30
+ shown,
31
+ source_numbers,
32
+ validate_section,
33
+ )
34
+ from memory_cli.syntheses.units import (
35
+ _FRONTMATTER_SLOT,
36
+ _GAP,
37
+ _REF_LINK,
38
+ _SUMMARY_SLOT,
39
+ _is_ref,
40
+ _parse,
41
+ _relative,
42
+ first_paragraph,
43
+ units,
44
+ without_references,
45
+ word_count,
46
+ )
47
+
48
+ if TYPE_CHECKING:
49
+ import datetime
50
+ from collections.abc import Callable, Sequence
51
+ from pathlib import Path
52
+ from typing import Unpack
53
+
54
+ from memory_cli.syntheses.document import Section, Synthesis
55
+ from memory_cli.syntheses.units import _Ref
56
+
57
+ MIN_SENTENCE_WORDS = 6
58
+ YAML_WIDTH = 10**6 # no line folding
59
+ SHRINK_RATIO = 0.8
60
+
61
+
62
+ def snapshot(path: Path):
63
+ """A function that puts back the synthesis and its curation log as they are now (for a write that must not
64
+ leave half a change when a later step fails)."""
65
+ log = path.parent / journal.CURATION_LOG
66
+ before = path.read_bytes()
67
+ log_before = log.read_bytes() if log.exists() else None
68
+
69
+ def undo() -> None:
70
+ safe_io.replace_file(path, before)
71
+ if log_before is None:
72
+ log.unlink(missing_ok=True)
73
+ else:
74
+ safe_io.replace_file(log, log_before)
75
+
76
+ return undo
77
+
78
+
79
+ def _clean(text: str) -> str:
80
+ return text.replace("\r\n", "\n").strip("\n")
81
+
82
+
83
+ def _check_body(text: str) -> None:
84
+ _, heads = _scan("---\nx: 1\n---\n" + text)
85
+ if heads:
86
+ raise ValueError(
87
+ f"the text contains a `## {heads[0][1]}` heading: a section is one heading and its text"
88
+ )
89
+
90
+
91
+ def _bump(text: str, today: datetime.date) -> str:
92
+ m = _FRONTMATTER.match(text)
93
+ if not m:
94
+ return text
95
+ head = re.sub(
96
+ r"^updated:[ \t]*.*$",
97
+ f"updated: '{today.isoformat()}'",
98
+ m.group(0),
99
+ count=1,
100
+ flags=re.MULTILINE,
101
+ )
102
+ return head + text[m.end() :]
103
+
104
+
105
+ def bumped(text: str, today: datetime.date) -> str:
106
+ """The file text with `updated:` set to `today`."""
107
+ return _bump(text, today)
108
+
109
+
110
+ def render_new(
111
+ template: str, *, title: str, topics: Sequence[str], summary: str, today: datetime.date
112
+ ) -> str:
113
+ """The template with `{frontmatter}` and `{summary}` filled in."""
114
+ meta = {
115
+ "title": title,
116
+ "topics": list(topics),
117
+ "created": today.isoformat(),
118
+ "updated": today.isoformat(),
119
+ }
120
+ head = yaml.safe_dump(
121
+ meta, sort_keys=False, allow_unicode=True, default_flow_style=None, width=YAML_WIDTH
122
+ )
123
+ return template.replace(_FRONTMATTER_SLOT, head).replace(_SUMMARY_SLOT, _clean(summary))
124
+
125
+
126
+ def create(folder: Path, slug: str, text: str) -> Path:
127
+ """Write a new synthesis file, never over an existing one."""
128
+ if not _HANDLE.fullmatch(slug):
129
+ raise ValueError(f"invalid slug {slug!r}: use lowercase letters, digits and hyphens")
130
+ folder.mkdir(parents=True, exist_ok=True)
131
+ path = folder / f"{slug}.md"
132
+ try:
133
+ with path.open("x", encoding="utf-8", newline="") as f:
134
+ f.write(text if text.endswith("\n") else text + "\n")
135
+ except FileExistsError:
136
+ raise ValueError(f"syntheses/{slug}.md already exists") from None
137
+ return path
138
+
139
+
140
+ def prepare_add(path: Path, heading: str, text: str, today: datetime.date) -> tuple[str, str, str]:
141
+ """Check an `add` without writing: (section handle, new file text, cleaned section text)."""
142
+ syn = load_one(path)
143
+ if syn.error:
144
+ raise ValueError(f"{path.name}: {syn.error}")
145
+ heading = " ".join(heading.split())
146
+ handle = section_handle(heading)
147
+ if not handle:
148
+ raise ValueError("the heading has no letters or digits")
149
+ if any(s.handle == handle for s in syn.sections):
150
+ raise ValueError(f"a section with the handle {handle!r} already exists")
151
+ text = _clean(text)
152
+ if not text:
153
+ raise ValueError("the section text is empty")
154
+ _check_body(text)
155
+ old = _read(path)
156
+ base = old if old.endswith("\n") else old + "\n"
157
+ new = base + ("" if base.endswith("\n\n") else "\n") + f"## {heading}\n\n{text}\n"
158
+ return handle, _bump(new, today), text
159
+
160
+
161
+ def add_section(path: Path, heading: str, text: str, today: datetime.date) -> str:
162
+ """Append `## heading` and its text; returns the section handle. Logs the previous file for undo."""
163
+ handle, new, _ = prepare_add(path, heading, text, today)
164
+ journal.log_before(load_one(path), "add")
165
+ _write(path, new)
166
+ return handle
167
+
168
+
169
+ def _target(path: Path, section: str) -> tuple[Synthesis, Section]:
170
+ syn = load_one(path)
171
+ if syn.error:
172
+ raise ValueError(f"{path.name}: {syn.error}")
173
+ target = next((s for s in syn.sections if s.handle == section), None)
174
+ if target is None:
175
+ raise ValueError(f"no section {section!r} in s:{syn.handle}")
176
+ if sum(1 for s in syn.sections if s.handle == section) > 1:
177
+ raise ValueError(
178
+ f"the handle {section!r} is repeated in s:{syn.handle}: rename one heading first"
179
+ )
180
+ return syn, target
181
+
182
+
183
+ def _replace(syn: Synthesis, target: Section, text: str, today: datetime.date, action: str) -> None:
184
+ path = syn.path
185
+ old = _read(path)
186
+ lines, heads = _scan(old)
187
+ n = next(k for k, (i, _) in enumerate(heads) if i + 1 == target.line)
188
+ end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
189
+ lines[heads[n][0] + 1 : end] = ["", *text.split("\n"), ""]
190
+ journal.log_before(syn, action)
191
+ _write(path, _bump("\n".join(lines), today))
192
+
193
+
194
+ def _sentences(text: str) -> list[str]:
195
+ """Sentences of at least six words, whitespace collapsed and lower-cased; split on `.`, `!`, `?` and line breaks."""
196
+ found = (" ".join(part.split()).lower() for part in re.split(r"[.!?\n]+", text))
197
+ return [s for s in found if len(s.split()) >= MIN_SENTENCE_WORDS]
198
+
199
+
200
+ def _guard_shrink(
201
+ old: str, new: str, *, sentences: bool = True, part: bool = False, drop_references: bool = False
202
+ ) -> None:
203
+ """Refuse a text that drops over 20% of the words, a link or, when `sentences`, a sentence of the old one
204
+ (a one-sentence field such as a claim is checked without the sentence rule). For a `part`, sentences are
205
+ compared without their references, and `drop_references` lets references go."""
206
+ dropped = max(word_count(old) - word_count(new), 0)
207
+ lost = list(dict.fromkeys(t for t in _links(old) if t not in set(_links(new))))
208
+ if drop_references:
209
+ lost = [t for t in lost if not _is_ref(t)]
210
+ old_s, new_s = (without_references(old), without_references(new)) if part else (old, new)
211
+ kept = set(_sentences(new_s))
212
+ gone = [s for s in dict.fromkeys(_sentences(old_s)) if s not in kept] if sentences else []
213
+ if lost or gone or word_count(new) < SHRINK_RATIO * word_count(old):
214
+ parts = [f"{n} {name}" for n, name in ((dropped, "words"), (len(gone), "sentences")) if n]
215
+ if lost:
216
+ parts.append(f"the links {', '.join(lost)}")
217
+ what = ", ".join(parts[:-1]) + (" and " if len(parts) > 1 else "") + parts[-1]
218
+ raise ValueError(f"the new text drops {what}; use --shrink if that is meant.")
219
+
220
+
221
+ def _link_on_sources(text: str, base: Path, target: str) -> tuple[str, str] | None:
222
+ """(label, target) as the part's `Sources:` line writes the note `target` names, or None."""
223
+ line = _sources_line(text) or ""
224
+ want = _resolved(base, target)
225
+ for m in _REF_LINK.finditer(line):
226
+ if _relative(m.group(2)) and _resolved(base, m.group(2)) == want:
227
+ return m.group(1), m.group(2)
228
+ return None
229
+
230
+
231
+ class _RefEditor:
232
+ """The state of one `change_references` call: the parsed part and the edits its proposals add up to."""
233
+
234
+ def __init__(self, text: str, base: Path) -> None:
235
+ self.text, self.base = text, base
236
+ self.found, self.refs, orphans, _ = _parse(text)
237
+ self.orphan_at = {r.start for r in orphans}
238
+ self.sources = {
239
+ _resolved(base, m.group(2))
240
+ for m in _REF_LINK.finditer(_sources_line(text) or "")
241
+ if _relative(m.group(2))
242
+ }
243
+ self.edits: list[
244
+ tuple[int, int, int, str]
245
+ ] = [] # (position, input order, end, replacement)
246
+ self.removed: dict[
247
+ int, set[int]
248
+ ] = {} # unit number -> starts of the trailing references to take out
249
+ self.seen: set[tuple[int, str, Path]] = set()
250
+
251
+ def judge(self, order: int, proposal: tuple[int, str, str]) -> str | None:
252
+ """Apply one proposal; the reason it was refused, or None."""
253
+ n, op, target = proposal
254
+ resolved = _resolved(self.base, target)
255
+ if not 1 <= n <= len(self.found):
256
+ return f"the part has no unit {n}"
257
+ if resolved not in self.sources:
258
+ return f"{target} is not on the part's Sources line"
259
+ if (n, op, resolved) in self.seen:
260
+ return f"the unit is already changed by an earlier line for {target}"
261
+ own = self._own(n, resolved)
262
+ reason = self._add(order, n, target, own) if op == "add" else self._remove(n, target, own)
263
+ if reason is None:
264
+ self.seen.add((n, op, resolved))
265
+ return reason
266
+
267
+ def _own(self, n: int, resolved: Path) -> list[_Ref]:
268
+ unit = self.found[n - 1]
269
+ return [
270
+ r
271
+ for r in self.refs
272
+ if unit.span[0] <= r.start < unit.span[1]
273
+ and r.start not in self.orphan_at
274
+ and _resolved(self.base, r.target) == resolved
275
+ ]
276
+
277
+ def _add(self, order: int, n: int, target: str, own: list[_Ref]) -> str | None:
278
+ unit = self.found[n - 1]
279
+ if own:
280
+ return f"unit {n} already carries {target}"
281
+ if unit.text.lstrip().startswith("|"):
282
+ return f"unit {n} is a table row"
283
+ link = _link_on_sources(self.text, self.base, target)
284
+ if link is None: # not reachable: the target is on the Sources line
285
+ return f"{target} is not on the part's Sources line"
286
+ self.edits.append((unit.span[1], order, unit.span[1], f" [{link[0]}]({link[1]})"))
287
+ return None
288
+
289
+ def _remove(self, n: int, target: str, own: list[_Ref]) -> str | None:
290
+ trailing = [r for r in own if r.trailing]
291
+ if not own:
292
+ return f"unit {n} does not carry {target}"
293
+ if not trailing:
294
+ return f"the reference to {target} in unit {n} is inside the sentence: it is part of its words"
295
+ self.removed.setdefault(n, set()).add(trailing[0].start)
296
+ return None
297
+
298
+ def _removal(self, n: int, gone: set[int]) -> tuple[int, int, int, str]:
299
+ """Write the unit's run of trailing references again without the removed ones, a space before each: taking
300
+ one out of `[a](x), [b](y)` must not leave its comma behind."""
301
+ unit = self.found[n - 1]
302
+ run = [
303
+ r
304
+ for r in self.refs
305
+ if r.trailing
306
+ and r.start not in self.orphan_at
307
+ and unit.span[0] <= r.start < unit.span[1]
308
+ ]
309
+ start = run[0].start
310
+ while start > unit.span[0] and self.text[start - 1] in _GAP:
311
+ start -= 1
312
+ kept = "".join(" " + self.text[r.start : r.end] for r in run if r.start not in gone)
313
+ return (start, -1, run[-1].end, kept)
314
+
315
+ def result(self) -> str:
316
+ edits = self.edits + [self._removal(n, gone) for n, gone in self.removed.items()]
317
+ out = self.text
318
+ for start, _, end, repl in sorted(edits, reverse=True):
319
+ out = out[:start] + repl + out[end:]
320
+ return out
321
+
322
+
323
+ def change_references(
324
+ text: str, base: Path, proposals: Sequence[tuple[int, str, str]]
325
+ ) -> tuple[str, list[str | None]]:
326
+ """A part's text with references added or removed, and per proposal `(unit number, "add" | "remove", target)`
327
+ the reason it was refused or None when it was applied. Every number refers to `text` as given; no word changes.
328
+
329
+ An add writes the label and target of the note's link on the `Sources:` line at the end of the unit, after any
330
+ references already there; a remove takes a reference that follows its sentence's closing punctuation, with the
331
+ white space before it, and never one inside the sentence. `base` is the folder the part's links are relative to."""
332
+ editor = _RefEditor(text, base)
333
+ reasons = [editor.judge(order, proposal) for order, proposal in enumerate(proposals)]
334
+ return editor.result(), reasons
335
+
336
+
337
+ def apply_part_text(path_text: str, section: str, new_text: str) -> str:
338
+ """The file text with the body of `section` replaced by `new_text`; every other byte stays."""
339
+ lines, heads = _scan(path_text)
340
+ n = next(k for k, (_, h) in enumerate(heads) if section_handle(h) == section)
341
+ end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
342
+ region = "\n".join(lines[heads[n][0] + 1 : end])
343
+ old = region.strip("\n")
344
+ at = region.find(old)
345
+ lines[heads[n][0] + 1 : end] = (region[:at] + new_text + region[at + len(old) :]).split("\n")
346
+ return "\n".join(lines)
347
+
348
+
349
+ def _guard_references(old: str, new: str) -> None:
350
+ """Refuse a new part that loses a reference of a sentence (or table row) it keeps word for word."""
351
+ kept: dict[str, set[str]] = {}
352
+ for u in units(new)[0]:
353
+ kept.setdefault(" ".join(u.plain.split()), set()).update(u.refs)
354
+ for u in units(old)[0]:
355
+ key = " ".join(u.plain.split())
356
+ if key in kept and (gone := [r for r in dict.fromkeys(u.refs) if r not in kept[key]]):
357
+ raise ValueError(
358
+ f"the new text drops the reference {gone[0]} from a sentence it keeps unchanged "
359
+ f"(unit {u.n}: {key[:60]!r}); use --drop-references if that is meant."
360
+ )
361
+
362
+
363
+ def _guard_shown(old: str, new: str) -> None:
364
+ """Refuse a new part written from the reader's form of the old one (`shown`), where a reference is only a number
365
+ or a label: saving it would lose the link."""
366
+ flat, numbers = " ".join(new.split()), source_numbers(old)
367
+ for u in units(old)[0]:
368
+ if u.refs and re.search(
369
+ re.escape(" ".join(shown(u.text, numbers).split())) + r"(?!\()", flat
370
+ ):
371
+ raise ValueError(
372
+ f"the new text has only the number or label of a reference of the stored part (unit {u.n}: "
373
+ f"{' '.join(u.plain.split())[:60]!r}); start from `mem show <part> --stored`, which "
374
+ "prints the references with their links."
375
+ )
376
+
377
+
378
+ class _EditOptions(TypedDict, total=False):
379
+ shrink: bool
380
+ drop_references: bool
381
+
382
+
383
+ def edit_section(
384
+ path: Path, section: str, text: str, today: datetime.date, **options: Unpack[_EditOptions]
385
+ ) -> None:
386
+ """Replace the text under one section's heading; every other byte of the file stays. Logs the previous file.
387
+
388
+ Refused, unless `shrink`, when the new text has under 80% of the words or lacks a link of the old one.
389
+ Refused, unless `drop_references` (whatever `shrink` says), when a sentence kept unchanged loses a reference."""
390
+ shrink = options.get("shrink", False)
391
+ drop_references = options.get("drop_references", False)
392
+ syn, target = _target(path, section)
393
+ text = _clean(text)
394
+ if not text:
395
+ raise ValueError("the section text is empty")
396
+ _check_body(text)
397
+ _guard_shown(target.text, text)
398
+ if not drop_references:
399
+ _guard_references(target.text, text)
400
+ if not shrink:
401
+ _guard_shrink(target.text, text, part=True, drop_references=drop_references)
402
+ _replace(syn, target, text, today, "edit")
403
+
404
+
405
+ def _without_sources(text: str, src: str | None) -> str:
406
+ if src is None:
407
+ return text.strip("\n")
408
+ lines = text.rstrip("\n").split("\n")
409
+ while lines and not lines[-1].strip():
410
+ lines.pop()
411
+ return "\n".join(lines[:-1]).strip("\n")
412
+
413
+
414
+ def _new_source_items(old_src: str | None, new_src: str | None) -> list[str]:
415
+ """The entries of `new_src` that the section's own `Sources:` line does not hold yet."""
416
+ if not new_src:
417
+ return []
418
+ have = old_src or ""
419
+ return [
420
+ i.strip()
421
+ for i in re.split(
422
+ r",\s*(?=\[|experience\b|https?://)", new_src.removeprefix("Sources:").strip()
423
+ )
424
+ if i.strip() and i.strip() not in have
425
+ ]
426
+
427
+
428
+ def _merged_sources(old_src: str | None, items: list[str]) -> str | None:
429
+ if old_src:
430
+ return old_src.rstrip() + "".join(", " + i for i in items)
431
+ return "Sources: " + ", ".join(items) if items else None
432
+
433
+
434
+ def append_text(
435
+ section_text: str, text: str, *, store: Path | None = None, is_summary: bool = False
436
+ ) -> str:
437
+ """The section text after `text` is added at its end, before its `Sources:` line; links of a closing `Sources:`
438
+ line in `text` join the section's own line. Writes nothing; pure unless `store` is given, which makes
439
+ `validate_section` read that store."""
440
+ text = _clean(text)
441
+ if not text:
442
+ raise ValueError("the text to append is empty")
443
+ _check_body(text)
444
+ old_src, new_src = _sources_line(section_text), _sources_line(text)
445
+ main, added = _without_sources(section_text, old_src), _without_sources(text, new_src)
446
+ items = _new_source_items(old_src, new_src)
447
+ src = _merged_sources(old_src, items)
448
+ if not added and not items:
449
+ raise ValueError("the text to append adds nothing")
450
+ new = "\n\n".join(p for p in (main, added, src) if p)
451
+ if store is not None and not is_summary and (problems := validate_section(new, store)):
452
+ raise ValueError("; ".join(problems))
453
+ return new
454
+
455
+
456
+ def append_section(
457
+ path: Path, section: str, text: str, today: datetime.date, *, store: Path | None = None
458
+ ) -> None:
459
+ """Add text at the end of a section, before its `Sources:` line; links of a closing `Sources:` line in `text`
460
+ join the section's own line."""
461
+ syn, target = _target(path, section)
462
+ new = append_text(target.text, text, store=store, is_summary=section == SUMMARY)
463
+ _replace(syn, target, new, today, "append")
464
+
465
+
466
+ def _section_lines(path: Path, section: str) -> tuple[str, list[str], list[tuple[int, str]], int]:
467
+ """(file text, its lines, its headings, index in the headings of `section`) from one read of the file."""
468
+ old = _read(path)
469
+ syn = load_one(path)
470
+ if syn.error:
471
+ raise ValueError(f"{path.name}: {syn.error}")
472
+ lines, heads = _scan(old)
473
+ found = [n for n, (_, h) in enumerate(heads) if section_handle(h) == section]
474
+ if not found:
475
+ raise ValueError(f"no section {section!r} in s:{syn.handle}")
476
+ if len(found) > 1:
477
+ raise ValueError(
478
+ f"the handle {section!r} is repeated in s:{syn.handle}: rename one heading by hand"
479
+ )
480
+ if section == SUMMARY:
481
+ raise ValueError("the summary cannot be renamed or removed")
482
+ return old, lines, heads, found[0]
483
+
484
+
485
+ def renamed_section(
486
+ path: Path, section: str, heading: str, today: datetime.date
487
+ ) -> tuple[str, str, str]:
488
+ """(old file text, new file text, new section handle) with the section's heading replaced; the text stays."""
489
+ old, lines, heads, n = _section_lines(path, section)
490
+ heading = " ".join(heading.split())
491
+ handle = section_handle(heading)
492
+ if not handle:
493
+ raise ValueError("the heading has no letters or digits")
494
+ if handle == SUMMARY or (
495
+ handle != section and any(section_handle(h) == handle for _, h in heads)
496
+ ):
497
+ raise ValueError(f"a section with the handle {handle!r} already exists")
498
+ i = heads[n][0]
499
+ lines[i] = f"## {heading}" + ("\r" if lines[i].endswith("\r") else "")
500
+ return old, _bump("\n".join(lines), today), handle
501
+
502
+
503
+ def without_section(path: Path, section: str, today: datetime.date) -> tuple[str, str]:
504
+ """(old file text, new file text) with the section's heading and text taken out; every other byte stays."""
505
+ old, lines, heads, n = _section_lines(path, section)
506
+ end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
507
+ del lines[heads[n][0] : end]
508
+ if n + 1 == len(heads): # the last one: the file ends with the text before it and one newline
509
+ while len(lines) > 1 and not lines[-1] and not lines[-2]:
510
+ lines.pop()
511
+ return old, _bump("\n".join(lines), today)
512
+
513
+
514
+ def _topics_range(lines: list[str], path: Path) -> tuple[int, int]:
515
+ """(first, end) indexes of the `topics` field in the frontmatter lines."""
516
+ start = next((i for i, ln in enumerate(lines) if ln.startswith(r"topics:")), None)
517
+ if start is None:
518
+ raise ValueError(f"{path.name} has no topics field")
519
+ end = start + 1
520
+ while end < len(lines) and re.match(r"(\s|- )", lines[end]):
521
+ end += 1
522
+ return start, end
523
+
524
+
525
+ def _check_topics(path: Path, new: str, topics: Sequence[str]) -> None:
526
+ head = _FRONTMATTER.match(new)
527
+ meta = safe_load(head.group(1)) if head else None
528
+ got = meta.get("topics") if isinstance(meta, dict) else None
529
+ if got != list(topics):
530
+ raise ValueError(
531
+ f"cannot rewrite the topics of {path.name}: edit its frontmatter by hand ({got!r})"
532
+ )
533
+
534
+
535
+ def with_topics(path: Path, topics: Sequence[str], today: datetime.date) -> tuple[str, str]:
536
+ """(old file text, new file text) with the frontmatter's `topics` replaced; every other byte stays."""
537
+ old = _read(path)
538
+ syn = load_one(path)
539
+ if syn.error:
540
+ raise ValueError(f"{path.name}: {syn.error}")
541
+ m = _FRONTMATTER.match(old)
542
+ if m is None:
543
+ raise ValueError(f"{path.name}: no YAML frontmatter")
544
+ if "\r" in m.group(0):
545
+ raise ValueError(f"{path.name} has CRLF line ends: convert it to LF first")
546
+ lines = m.group(1).split("\n")
547
+ start, end = _topics_range(lines, path)
548
+ rendered = yaml.safe_dump(
549
+ list(topics), allow_unicode=True, default_flow_style=True, width=YAML_WIDTH
550
+ ).split("\n")[0]
551
+ lines[start:end] = [f"topics: {rendered}"]
552
+ new = _bump("---\n" + "\n".join(lines) + "\n---\n" + old[m.end() :], today)
553
+ _check_topics(path, new, topics)
554
+ return old, new
555
+
556
+
557
+ def match_sections(
558
+ syntheses: Sequence[Synthesis],
559
+ query_tokens: Sequence[str],
560
+ *,
561
+ tokenize: Callable[[str], list[str]],
562
+ limit: int = 2,
563
+ ) -> list[tuple[Synthesis, Section]]:
564
+ """Sections holding at least half (rounded up) of the query's non-stop-word terms in heading and first paragraph.
565
+
566
+ Best first: most terms in the heading, then most overall, then handle."""
567
+ terms = set(query_tokens) - STOPWORDS
568
+ if not terms:
569
+ return []
570
+ need = (len(terms) + 1) // 2
571
+ scored = []
572
+ for syn in syntheses:
573
+ if syn.error is not None:
574
+ continue
575
+ for sec in syn.sections:
576
+ in_heading = terms & set(tokenize(sec.heading))
577
+ overall = terms & set(tokenize(sec.heading + " " + first_paragraph(sec.text)))
578
+ if len(overall) >= need:
579
+ scored.append((syn, sec, len(in_heading), len(overall)))
580
+ scored.sort(key=lambda t: (-t[2], -t[3], t[0].handle, t[1].line))
581
+ return [(s, sec) for s, sec, _, _ in scored[:limit]]