memory-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1122 @@
|
|
|
1
|
+
"""The synthesis handlers (A5, ADR 0028): `synthesis` and `project-synthesis`, with the logic only they use (the structure and refs commands, section-with-note writes, the logged multi-file write, the project-synthesis handlers)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import datetime
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import sys
|
|
11
|
+
import uuid
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
|
|
18
|
+
from memory_cli.commands import common, edit
|
|
19
|
+
from memory_cli.core import safe_io
|
|
20
|
+
from memory_cli.memories import records
|
|
21
|
+
from memory_cli.notes import check as check_rules
|
|
22
|
+
from memory_cli.notes import index as index_files
|
|
23
|
+
from memory_cli.notes import note as note_files
|
|
24
|
+
from memory_cli.syntheses import document, units
|
|
25
|
+
from memory_cli.syntheses import edit as synthesis_edit
|
|
26
|
+
from memory_cli.syntheses import project as project_syntheses
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
import argparse
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
|
|
32
|
+
_SETTLE_LOG_CELLS = 3 # `<section> | <unit> | add|remove <target>`
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_SETTLE_ACTION_WORDS = 2 # `add|remove <target>`
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _warn_uncommitted(ref: str) -> None:
|
|
39
|
+
print(
|
|
40
|
+
f"mem: {ref} covers files with uncommitted changes; "
|
|
41
|
+
"it will read possibly stale until you confirm it after committing.",
|
|
42
|
+
file=sys.stderr,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _ps_list(args: argparse.Namespace, memory_dir: Path, tree: Path) -> int:
|
|
47
|
+
found, broken = project_syntheses.load_each(memory_dir)
|
|
48
|
+
for name, parts in found.items():
|
|
49
|
+
for part in parts:
|
|
50
|
+
print(common._part_line(name, part, tree))
|
|
51
|
+
for path, error in broken:
|
|
52
|
+
print(f"mem: skipped {path}: {error}", file=sys.stderr)
|
|
53
|
+
return 1 if broken else 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _ps_check_name(name: str) -> None:
|
|
57
|
+
if name not in project_syntheses.NAMES:
|
|
58
|
+
raise project_syntheses.ProjectSynthesisError(
|
|
59
|
+
f"unknown project synthesis {name!r}; use one of: {', '.join(project_syntheses.NAMES)}"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _ps_add(args: argparse.Namespace, memory_dir: Path, tree: Path) -> int:
|
|
64
|
+
try:
|
|
65
|
+
body = common._memory_body(args.body_file)
|
|
66
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
67
|
+
print(f"mem: cannot read the body: {exc}", file=sys.stderr)
|
|
68
|
+
return 2
|
|
69
|
+
_ps_check_name(args.name)
|
|
70
|
+
paths = [p for p in (item.strip() for item in args.paths.split(",")) if p]
|
|
71
|
+
project_syntheses._check_paths(
|
|
72
|
+
tree, paths
|
|
73
|
+
) # before the secret scan, so a bad path is not reported as a secret
|
|
74
|
+
if common._refuse_secret([args.heading, body]):
|
|
75
|
+
return 4
|
|
76
|
+
handle = project_syntheses.write_part(
|
|
77
|
+
memory_dir,
|
|
78
|
+
tree,
|
|
79
|
+
project_syntheses.NewPart(args.name, args.heading, body, paths),
|
|
80
|
+
datetime.date.today(),
|
|
81
|
+
)
|
|
82
|
+
ref = f"p:{args.name}#{handle}"
|
|
83
|
+
print(ref)
|
|
84
|
+
if project_syntheses.covers_uncommitted(tree, paths):
|
|
85
|
+
_warn_uncommitted(ref)
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _ps_confirm(args: argparse.Namespace, memory_dir: Path, tree: Path) -> int:
|
|
90
|
+
name, handle = common._split_part_ref(args.part)
|
|
91
|
+
found = common._load_project_syntheses(memory_dir, name)
|
|
92
|
+
if handle is None or name not in found or handle not in [p.handle for p in found[name]]:
|
|
93
|
+
raise project_syntheses.Unavailable(
|
|
94
|
+
f"no part {args.part!r}; parts that exist: {common._existing_parts(found)}"
|
|
95
|
+
)
|
|
96
|
+
project_syntheses.confirm_part(memory_dir, tree, name, handle, datetime.date.today())
|
|
97
|
+
print(
|
|
98
|
+
f"p:{name}#{handle}\tconfirmed at {project_syntheses.head_commit(tree) or project_syntheses.NO_COMMIT}"
|
|
99
|
+
)
|
|
100
|
+
part = next(p for p in found[name] if p.handle == handle)
|
|
101
|
+
if project_syntheses.covers_uncommitted(tree, part.stamp.paths):
|
|
102
|
+
_warn_uncommitted(f"p:{name}#{handle}")
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
_PS_HANDLERS = {"list": _ps_list, "add": _ps_add}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_project_synthesis(args: argparse.Namespace) -> int:
|
|
110
|
+
context = common._project_synthesis_context()
|
|
111
|
+
if context is None:
|
|
112
|
+
return 2
|
|
113
|
+
memory_dir, tree, _ = context
|
|
114
|
+
try:
|
|
115
|
+
return _PS_HANDLERS.get(args.ps_command, _ps_confirm)(args, memory_dir, tree)
|
|
116
|
+
except project_syntheses.ProjectSynthesisError as exc:
|
|
117
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
118
|
+
return 1 if isinstance(exc, project_syntheses.Unavailable) else 2
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _synthesis_text(source: str | None) -> str | None:
|
|
122
|
+
try:
|
|
123
|
+
return common._read_body(source) if source else ""
|
|
124
|
+
except common.NewNoteError as exc:
|
|
125
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _long_note(handle: str, path: Path, section: str) -> None:
|
|
130
|
+
sec = next((x for x in document.load_one(path).sections if x.handle == section), None)
|
|
131
|
+
if sec is not None and (n := units.word_count(sec.text)) > document.LONG_SECTION_WORDS:
|
|
132
|
+
print(
|
|
133
|
+
f"mem: s:{handle}#{section} has {n} words: consider splitting it into two parts "
|
|
134
|
+
"(mem synthesis add).",
|
|
135
|
+
file=sys.stderr,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _part_of_notes(root: Path, ref: str) -> list[tuple[Path, str]]:
|
|
140
|
+
"""(path, text) of each note whose `part_of` is `ref` (`<synthesis>#<section>`), sorted by path."""
|
|
141
|
+
found = []
|
|
142
|
+
for _, path in note_files._note_files(root):
|
|
143
|
+
try:
|
|
144
|
+
text = path.read_bytes().decode("utf-8")
|
|
145
|
+
meta = note_files.split_frontmatter(text)[0]
|
|
146
|
+
except (OSError, UnicodeDecodeError, note_files.FrontmatterError):
|
|
147
|
+
continue
|
|
148
|
+
if isinstance(meta, dict) and meta.get("part_of") == ref:
|
|
149
|
+
found.append((path, text))
|
|
150
|
+
return sorted(found)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _log_group_ahead(root: Path, changes: Mapping[Path, tuple[bytes, bytes]], action: str) -> str:
|
|
154
|
+
"""The group entries `_log_group` writes, but before the files change: each holds the digest of the new bytes.
|
|
155
|
+
Returns the group id."""
|
|
156
|
+
group = uuid.uuid4().hex
|
|
157
|
+
stamp = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
158
|
+
safe_io.append_text(
|
|
159
|
+
root / records.CURATION_LOG,
|
|
160
|
+
"".join(
|
|
161
|
+
json.dumps(
|
|
162
|
+
{
|
|
163
|
+
"t": stamp,
|
|
164
|
+
"action": action,
|
|
165
|
+
"handle": path.relative_to(root).as_posix(),
|
|
166
|
+
"group": group,
|
|
167
|
+
"before": old.decode("utf-8"),
|
|
168
|
+
"after": common._sha(new),
|
|
169
|
+
},
|
|
170
|
+
ensure_ascii=False,
|
|
171
|
+
)
|
|
172
|
+
+ "\n"
|
|
173
|
+
for path, (old, new) in changes.items()
|
|
174
|
+
),
|
|
175
|
+
)
|
|
176
|
+
return group
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _logged_changes_unchanged(changes: Mapping[Path, tuple[bytes, bytes]]) -> None:
|
|
180
|
+
"""ValueError when a file is not as it was read."""
|
|
181
|
+
for path, (old, _) in changes.items():
|
|
182
|
+
if path.read_bytes() != old:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
f"{path.name} changed since it was read, so nothing was written: run the command again"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _write_logged_changes(
|
|
189
|
+
changes: Mapping[Path, tuple[bytes, bytes]], log: Path, write_log: Callable[[], object]
|
|
190
|
+
) -> None:
|
|
191
|
+
"""Log the undo with `write_log`, then swap each file from its old bytes to its new ones; a file that is not as
|
|
192
|
+
it was read, or any failure, puts every file and `log` back as they were."""
|
|
193
|
+
log_before = log.read_bytes() if log.exists() else None
|
|
194
|
+
write_log()
|
|
195
|
+
swapped: list[Path] = []
|
|
196
|
+
try:
|
|
197
|
+
_logged_changes_unchanged(changes)
|
|
198
|
+
for path, (_, new) in changes.items():
|
|
199
|
+
common._swap_file(path, new)
|
|
200
|
+
swapped.append(path)
|
|
201
|
+
except BaseException:
|
|
202
|
+
for path in swapped:
|
|
203
|
+
common._swap_file(path, changes[path][0])
|
|
204
|
+
if log_before is None:
|
|
205
|
+
log.unlink(missing_ok=True)
|
|
206
|
+
else:
|
|
207
|
+
safe_io.replace_file(log, log_before)
|
|
208
|
+
raise
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _synthesis_require_writable(changes: Mapping[Path, tuple[bytes, bytes]]) -> None:
|
|
212
|
+
"""ValueError naming the files of `changes` that cannot be written."""
|
|
213
|
+
locked = [
|
|
214
|
+
p.name for p in changes if not os.access(p, os.W_OK) or not os.access(p.parent, os.W_OK)
|
|
215
|
+
]
|
|
216
|
+
if locked:
|
|
217
|
+
raise ValueError(f"not writable: {', '.join(locked)}")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@dataclass(frozen=True)
|
|
221
|
+
class _StructurePlan:
|
|
222
|
+
"""What a `mem synthesis` structure command will write: the files with their old and new bytes, the output
|
|
223
|
+
lines, the curation log and the function that logs the undo."""
|
|
224
|
+
|
|
225
|
+
changes: dict[Path, tuple[bytes, bytes]]
|
|
226
|
+
lines: list[str]
|
|
227
|
+
log: Path
|
|
228
|
+
write_log: Callable[[], object]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(frozen=True)
|
|
232
|
+
class _StructureTarget:
|
|
233
|
+
"""The synthesis (and section, when given) a structure command acts on."""
|
|
234
|
+
|
|
235
|
+
root: Path
|
|
236
|
+
handle: str
|
|
237
|
+
section: str | None
|
|
238
|
+
path: Path
|
|
239
|
+
today: datetime.date
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@dataclass(frozen=True)
|
|
243
|
+
class _SectionEdit:
|
|
244
|
+
"""The new text of a synthesis after a section changed, the output lines, and how each member note changes."""
|
|
245
|
+
|
|
246
|
+
old: str
|
|
247
|
+
new: str
|
|
248
|
+
lines: list[str]
|
|
249
|
+
edit_note: Callable[[str, str], str]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _structure_detach_plan(root: Path, note: str) -> _StructurePlan | None:
|
|
253
|
+
"""The plan to detach a note from its synthesis; None after an ambiguity message on stderr."""
|
|
254
|
+
found = common.resolve_note(root, note)
|
|
255
|
+
if isinstance(found, list):
|
|
256
|
+
common._ambiguous(note, found)
|
|
257
|
+
return None
|
|
258
|
+
if found is None or found not in {p.resolve() for _, p in note_files._note_files(root)}:
|
|
259
|
+
raise ValueError(f"no note {note}")
|
|
260
|
+
rel = found.relative_to(root).as_posix()
|
|
261
|
+
original = found.read_bytes()
|
|
262
|
+
text = original.decode("utf-8")
|
|
263
|
+
meta = note_files.split_frontmatter(text)[0]
|
|
264
|
+
part = meta.get("part_of") if isinstance(meta, dict) else None
|
|
265
|
+
if not isinstance(part, str):
|
|
266
|
+
raise edit.NoteFormatError(f"{note_files._handle(rel)} is not part of a synthesis")
|
|
267
|
+
return _StructurePlan(
|
|
268
|
+
{found: (original, _detached(text, rel).encode("utf-8"))},
|
|
269
|
+
[f"{note_files._handle(rel)}\tdetached from s:{part}"],
|
|
270
|
+
root / records.CURATION_LOG,
|
|
271
|
+
lambda: edit._log_note(root, found, rel, "detach"),
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _structure_topic_ids(args: argparse.Namespace, root: Path) -> list[str]:
|
|
276
|
+
"""The topic ids of `mem synthesis topics`, each one known; ValueError otherwise."""
|
|
277
|
+
topics = list(dict.fromkeys(t.strip() for t in args.topic_ids.split(",") if t.strip()))
|
|
278
|
+
known = note_files.load_topics(root)
|
|
279
|
+
if not topics:
|
|
280
|
+
raise ValueError("at least one topic is required")
|
|
281
|
+
for t in topics:
|
|
282
|
+
if t not in known:
|
|
283
|
+
raise ValueError(f"unknown topic '{t}': use an id from topics.yaml or add it there")
|
|
284
|
+
return topics
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _structure_topic_clash(root: Path, handle: str, topics: Sequence[str]) -> None:
|
|
288
|
+
"""ValueError when another synthesis already covers one of `topics`."""
|
|
289
|
+
for other in document.load(root / document.SYNTHESES_DIR):
|
|
290
|
+
if (
|
|
291
|
+
other.error is None
|
|
292
|
+
and other.handle != handle
|
|
293
|
+
and (clash := [t for t in topics if t in other.topics])
|
|
294
|
+
):
|
|
295
|
+
raise ValueError(f"s:{other.handle} already covers the topic {clash[0]}")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _structure_topics_plan(args: argparse.Namespace, target: _StructureTarget) -> _StructurePlan:
|
|
299
|
+
if target.section is not None:
|
|
300
|
+
raise ValueError("topics takes s:<handle>")
|
|
301
|
+
topics = _structure_topic_ids(args, target.root)
|
|
302
|
+
_structure_topic_clash(target.root, target.handle, topics)
|
|
303
|
+
old, new = synthesis_edit.with_topics(target.path, topics, target.today)
|
|
304
|
+
return _StructurePlan(
|
|
305
|
+
{target.path: (old.encode("utf-8"), new.encode("utf-8"))},
|
|
306
|
+
[f"s:{target.handle}\ttopics {', '.join(topics)}"],
|
|
307
|
+
target.root / document.SYNTHESES_DIR / records.CURATION_LOG,
|
|
308
|
+
lambda: records.log_before(document.Synthesis(target.path, target.handle), "topics"),
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _structure_rename_edit(
|
|
313
|
+
args: argparse.Namespace, target: _StructureTarget, members: Sequence[tuple[Path, str]]
|
|
314
|
+
) -> _SectionEdit:
|
|
315
|
+
section = cast("str", target.section)
|
|
316
|
+
old, new, new_section = synthesis_edit.renamed_section(
|
|
317
|
+
target.path, section, args.heading, target.today
|
|
318
|
+
)
|
|
319
|
+
return _SectionEdit(
|
|
320
|
+
old,
|
|
321
|
+
new,
|
|
322
|
+
[
|
|
323
|
+
f"s:{target.handle}#{new_section}\trenamed from {section}",
|
|
324
|
+
*[
|
|
325
|
+
f"{note_files._handle(p.relative_to(target.root).as_posix())}\tpart of s:{target.handle}#{new_section}"
|
|
326
|
+
for p, _ in members
|
|
327
|
+
],
|
|
328
|
+
],
|
|
329
|
+
lambda text, rel: _renamed_part_of(text, rel, f"{target.handle}#{new_section}"),
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _structure_remove_edit(
|
|
334
|
+
target: _StructureTarget, members: Sequence[tuple[Path, str]]
|
|
335
|
+
) -> _SectionEdit:
|
|
336
|
+
section = cast("str", target.section)
|
|
337
|
+
old, new = synthesis_edit.without_section(target.path, section, target.today)
|
|
338
|
+
ref = f"{target.handle}#{section}"
|
|
339
|
+
return _SectionEdit(
|
|
340
|
+
old,
|
|
341
|
+
new,
|
|
342
|
+
[
|
|
343
|
+
f"s:{ref}\tremoved",
|
|
344
|
+
*[
|
|
345
|
+
f"{note_files._handle(p.relative_to(target.root).as_posix())}\tdetached from s:{ref}"
|
|
346
|
+
for p, _ in members
|
|
347
|
+
],
|
|
348
|
+
],
|
|
349
|
+
_detached,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _structure_section_plan(
|
|
354
|
+
args: argparse.Namespace, target: _StructureTarget, action: str
|
|
355
|
+
) -> _StructurePlan:
|
|
356
|
+
"""The plan to rename or remove one section, with the member notes that follow it."""
|
|
357
|
+
if target.section is None:
|
|
358
|
+
raise ValueError(f"{action} takes s:<handle>#<section handle>")
|
|
359
|
+
root = target.root
|
|
360
|
+
members = _part_of_notes(root, f"{target.handle}#{target.section}")
|
|
361
|
+
edit = (
|
|
362
|
+
_structure_rename_edit(args, target, members)
|
|
363
|
+
if action == "rename"
|
|
364
|
+
else _structure_remove_edit(target, members)
|
|
365
|
+
)
|
|
366
|
+
changes = {target.path: (edit.old.encode("utf-8"), edit.new.encode("utf-8"))}
|
|
367
|
+
for note, text in members:
|
|
368
|
+
changes[note] = (
|
|
369
|
+
text.encode("utf-8"),
|
|
370
|
+
edit.edit_note(text, note.relative_to(root).as_posix()).encode("utf-8"),
|
|
371
|
+
)
|
|
372
|
+
return _StructurePlan(
|
|
373
|
+
changes,
|
|
374
|
+
edit.lines,
|
|
375
|
+
root / records.CURATION_LOG,
|
|
376
|
+
lambda: _log_group_ahead(root, changes, action),
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _structure_plan(
|
|
381
|
+
args: argparse.Namespace, root: Path, action: str, today: datetime.date
|
|
382
|
+
) -> _StructurePlan | None:
|
|
383
|
+
"""The plan of a structure command; None after a message on stderr."""
|
|
384
|
+
if action == "detach":
|
|
385
|
+
return _structure_detach_plan(root, args.note)
|
|
386
|
+
handle, section = document.split_ref(args.target)
|
|
387
|
+
path = document.path_of(root / document.SYNTHESES_DIR, handle)
|
|
388
|
+
if path is None or not path.is_file():
|
|
389
|
+
raise ValueError(f"no synthesis named {args.target}")
|
|
390
|
+
target = _StructureTarget(root, handle, section, path, today)
|
|
391
|
+
if action == "topics":
|
|
392
|
+
return _structure_topics_plan(args, target)
|
|
393
|
+
return _structure_section_plan(args, target, action)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _structure_heading_refused(args: argparse.Namespace) -> int:
|
|
397
|
+
"""0 when the new heading may be written, else the exit code after a message on stderr."""
|
|
398
|
+
if common._refuse_secret([args.heading]):
|
|
399
|
+
return 4
|
|
400
|
+
return common._check_terms([args.heading], "synthesis", getattr(args, "owner_approved", False))
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _structure_run(
|
|
404
|
+
args: argparse.Namespace, root: Path, action: str, today: datetime.date
|
|
405
|
+
) -> tuple[int, list[str]]:
|
|
406
|
+
"""(exit code, output lines) after the files of the command were written; the lines only when the code is 0."""
|
|
407
|
+
if action == "rename":
|
|
408
|
+
refused = _structure_heading_refused(args)
|
|
409
|
+
if refused:
|
|
410
|
+
return refused, []
|
|
411
|
+
plan = _structure_plan(args, root, action, today)
|
|
412
|
+
if plan is None:
|
|
413
|
+
return 2, []
|
|
414
|
+
_synthesis_require_writable(plan.changes)
|
|
415
|
+
_write_logged_changes(plan.changes, plan.log, plan.write_log)
|
|
416
|
+
return 0, plan.lines
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _structure(args: argparse.Namespace) -> int:
|
|
420
|
+
"""`mem synthesis rename | remove | detach | topics`: one line per changed record, errors on stderr with exit 2."""
|
|
421
|
+
root = args.root.resolve()
|
|
422
|
+
action = args.synthesis_command
|
|
423
|
+
try:
|
|
424
|
+
code, lines = _structure_run(args, root, action, datetime.date.today())
|
|
425
|
+
except (
|
|
426
|
+
common.NewNoteError,
|
|
427
|
+
OSError,
|
|
428
|
+
ValueError,
|
|
429
|
+
note_files.FrontmatterError,
|
|
430
|
+
yaml.YAMLError,
|
|
431
|
+
) as exc:
|
|
432
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
433
|
+
return 2
|
|
434
|
+
if code != 0:
|
|
435
|
+
return code
|
|
436
|
+
print("\n".join(lines))
|
|
437
|
+
common.log_usage(root, {"cmd": "synthesis", "action": action})
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
@dataclass(frozen=True)
|
|
442
|
+
class _RefsPart:
|
|
443
|
+
"""One part of a synthesis with the reference changes proposed for it, each (line, unit, op, target)."""
|
|
444
|
+
|
|
445
|
+
part: document.Section
|
|
446
|
+
items: list[tuple[str, int, str, str]]
|
|
447
|
+
folder: Path
|
|
448
|
+
root: Path
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@dataclass(frozen=True)
|
|
452
|
+
class _RefsPartOutcome:
|
|
453
|
+
"""What the proposals for one part came to: refused lines, the summary line (None when the part was refused as
|
|
454
|
+
a whole), the units added and removed, and (old, new) text of the part when it changed."""
|
|
455
|
+
|
|
456
|
+
refused: list[str]
|
|
457
|
+
count_line: str | None
|
|
458
|
+
added: int
|
|
459
|
+
removed: int
|
|
460
|
+
change: tuple[str, str] | None
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
@dataclass(frozen=True)
|
|
464
|
+
class _RefsOutcome:
|
|
465
|
+
"""What the proposals came to over the whole synthesis: its new text, the member notes to rewrite, one summary
|
|
466
|
+
line per part, the refused lines and the totals."""
|
|
467
|
+
|
|
468
|
+
new_file: str
|
|
469
|
+
notes: dict[Path, tuple[bytes, bytes]]
|
|
470
|
+
counts: list[str]
|
|
471
|
+
refused: list[str]
|
|
472
|
+
added: int
|
|
473
|
+
removed: int
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
@dataclass(frozen=True)
|
|
477
|
+
class _RefsRun:
|
|
478
|
+
"""The result of `mem synthesis refs` before it prints: exit code, output lines, whether a file changed."""
|
|
479
|
+
|
|
480
|
+
code: int
|
|
481
|
+
lines: list[str]
|
|
482
|
+
changed: bool
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _refs_target(target: str, folder: Path) -> tuple[str, Path] | None:
|
|
486
|
+
"""(handle, path) of the synthesis named; None after a message on stderr when there is none."""
|
|
487
|
+
handle, section = document.split_ref(target)
|
|
488
|
+
path = document.path_of(folder, handle)
|
|
489
|
+
if path is None or not path.is_file():
|
|
490
|
+
print(f"mem: no synthesis named {target}", file=sys.stderr)
|
|
491
|
+
return None
|
|
492
|
+
if section is not None:
|
|
493
|
+
raise ValueError("refs takes s:<handle>")
|
|
494
|
+
return handle, path
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _refs_read_file(file: str) -> str | None:
|
|
498
|
+
"""The proposal file; None after a message on stderr when it cannot be read."""
|
|
499
|
+
try:
|
|
500
|
+
return Path(file).read_text(encoding="utf-8")
|
|
501
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
502
|
+
print(f"mem: cannot read the file: {exc}", file=sys.stderr)
|
|
503
|
+
return None
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _refs_parse_line(line: str) -> tuple[str, tuple[str, int, str, str]] | None:
|
|
507
|
+
"""(section handle, (line, unit, op, target)) of a proposal line; None when it is not one."""
|
|
508
|
+
cells = [c.strip() for c in line.split("|", 2)]
|
|
509
|
+
action = cells[2].split(None, 1) if len(cells) == _SETTLE_LOG_CELLS else []
|
|
510
|
+
if not (
|
|
511
|
+
len(cells) == _SETTLE_LOG_CELLS
|
|
512
|
+
and cells[1].isdigit()
|
|
513
|
+
and len(action) == _SETTLE_ACTION_WORDS
|
|
514
|
+
and action[0] in {"add", "remove"}
|
|
515
|
+
):
|
|
516
|
+
return None
|
|
517
|
+
return cells[0], (line.strip(), int(cells[1]), action[0], action[1].strip())
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _refs_proposals(
|
|
521
|
+
raw: str,
|
|
522
|
+
) -> tuple[dict[str, list[tuple[str, int, str, str]]], list[str]]:
|
|
523
|
+
"""The proposals of the file by section handle, and a refused line for each one that is malformed."""
|
|
524
|
+
refused: list[str] = []
|
|
525
|
+
by_part: dict[str, list[tuple[str, int, str, str]]] = {}
|
|
526
|
+
for line in raw.splitlines():
|
|
527
|
+
if not line.strip() or line.lstrip().startswith("#"):
|
|
528
|
+
continue
|
|
529
|
+
parsed = _refs_parse_line(line)
|
|
530
|
+
if parsed is None:
|
|
531
|
+
refused.append(
|
|
532
|
+
f"refused: {line.strip()}: not `<section> | <unit> | add|remove <target>`"
|
|
533
|
+
)
|
|
534
|
+
continue
|
|
535
|
+
by_part.setdefault(parsed[0], []).append(parsed[1])
|
|
536
|
+
return by_part, refused
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _refs_refusal(
|
|
540
|
+
sections: Sequence[document.Section], name: str, part: document.Section | None
|
|
541
|
+
) -> str | None:
|
|
542
|
+
"""Why no reference may change in the part `name`; None when it may."""
|
|
543
|
+
if name == document.SUMMARY:
|
|
544
|
+
return "the Summary takes no references"
|
|
545
|
+
if part is None:
|
|
546
|
+
return f"no section {name!r}"
|
|
547
|
+
if sum(1 for x in sections if x.handle == name) > 1:
|
|
548
|
+
return f"the handle {name!r} is repeated: rename one heading first"
|
|
549
|
+
return None
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _refs_attempt(unit: _RefsPart, picked: list[int]) -> tuple[str, list[str | None], str | None]:
|
|
553
|
+
"""The part's text with the picked proposals applied, the reason each was refused, and a problem with the
|
|
554
|
+
result as a whole (None when it is sound)."""
|
|
555
|
+
part = unit.part
|
|
556
|
+
text, why_not = synthesis_edit.change_references(
|
|
557
|
+
part.text,
|
|
558
|
+
unit.folder,
|
|
559
|
+
[(unit.items[i][1], unit.items[i][2], unit.items[i][3]) for i in picked],
|
|
560
|
+
)
|
|
561
|
+
if text == part.text:
|
|
562
|
+
return text, why_not, None
|
|
563
|
+
if units.without_references(text) != units.without_references(part.text):
|
|
564
|
+
return (
|
|
565
|
+
text,
|
|
566
|
+
why_not,
|
|
567
|
+
"the command would change a word of the part (a bug: nothing of it was written)",
|
|
568
|
+
)
|
|
569
|
+
if found := document.validate_section(text, unit.root):
|
|
570
|
+
return text, why_not, "the part would fail its checks: " + "; ".join(found)
|
|
571
|
+
return text, why_not, None
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _refs_resolve(unit: _RefsPart) -> tuple[str, list[str | None]]:
|
|
575
|
+
"""The part's new text and the reason each proposal was refused (None when applied)."""
|
|
576
|
+
everyone = list(range(len(unit.items)))
|
|
577
|
+
new, reasons, problem = _refs_attempt(unit, everyone)
|
|
578
|
+
if problem:
|
|
579
|
+
# One line that breaks the part is refused alone; the others are applied unit by unit.
|
|
580
|
+
reasons, kept = list(reasons), []
|
|
581
|
+
for i in everyone:
|
|
582
|
+
if reasons[i] is not None:
|
|
583
|
+
continue
|
|
584
|
+
if (trial := _refs_attempt(unit, [*kept, i]))[2]:
|
|
585
|
+
reasons[i] = trial[2]
|
|
586
|
+
else:
|
|
587
|
+
kept.append(i)
|
|
588
|
+
new = _refs_attempt(unit, kept)[0]
|
|
589
|
+
return new, reasons
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _refs_count(
|
|
593
|
+
items: Sequence[tuple[str, int, str, str]], reasons: Sequence[str | None], op: str
|
|
594
|
+
) -> int:
|
|
595
|
+
"""How many proposals of kind `op` were applied."""
|
|
596
|
+
return sum(1 for (_, _, o, _), r in zip(items, reasons, strict=False) if r is None and o == op)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _refs_part_outcome(
|
|
600
|
+
sections: Sequence[document.Section],
|
|
601
|
+
handle: str,
|
|
602
|
+
root: Path,
|
|
603
|
+
name: str,
|
|
604
|
+
items: list[tuple[str, int, str, str]],
|
|
605
|
+
) -> _RefsPartOutcome:
|
|
606
|
+
part = {s.handle: s for s in sections}.get(name)
|
|
607
|
+
why = _refs_refusal(sections, name, part)
|
|
608
|
+
if why or part is None: # `part` is None only when `why` is set
|
|
609
|
+
return _RefsPartOutcome([f"refused: {line}: {why}" for line, *_ in items], None, 0, 0, None)
|
|
610
|
+
new, reasons = _refs_resolve(_RefsPart(part, items, root / document.SYNTHESES_DIR, root))
|
|
611
|
+
failed = [
|
|
612
|
+
f"refused: {line}: {r}"
|
|
613
|
+
for (line, *_), r in zip(items, reasons, strict=False)
|
|
614
|
+
if r is not None
|
|
615
|
+
]
|
|
616
|
+
added = _refs_count(items, reasons, "add")
|
|
617
|
+
removed = _refs_count(items, reasons, "remove")
|
|
618
|
+
return _RefsPartOutcome(
|
|
619
|
+
failed,
|
|
620
|
+
f"s:{handle}#{name}: added {added}, removed {removed}, refused {len(failed)}",
|
|
621
|
+
added,
|
|
622
|
+
removed,
|
|
623
|
+
(part.text, new) if new != part.text else None,
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _refs_note_edits(
|
|
628
|
+
root: Path, handle: str, name: str, change: tuple[str, str]
|
|
629
|
+
) -> dict[Path, tuple[bytes, bytes]]:
|
|
630
|
+
"""The member notes of a changed part that were current and get the new `part_of_hash`."""
|
|
631
|
+
old, new = change
|
|
632
|
+
notes: dict[Path, tuple[bytes, bytes]] = {}
|
|
633
|
+
for note, text in _part_of_notes(root, f"{handle}#{name}"):
|
|
634
|
+
stored = (note_files.split_frontmatter(text)[0] or {}).get("part_of_hash")
|
|
635
|
+
rel = note.relative_to(root).as_posix()
|
|
636
|
+
new_fp = units.note_fingerprint(new, common._note_target(rel))
|
|
637
|
+
if units.is_current(stored, old, common._note_target(rel)) and stored != new_fp:
|
|
638
|
+
notes[note] = (
|
|
639
|
+
text.encode("utf-8"),
|
|
640
|
+
common._set_field(edit._lf(text, rel), "part_of_hash", new_fp).encode("utf-8"),
|
|
641
|
+
)
|
|
642
|
+
return notes
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _refs_collect(
|
|
646
|
+
syn: document.Synthesis,
|
|
647
|
+
handle: str,
|
|
648
|
+
root: Path,
|
|
649
|
+
by_part: dict[str, list[tuple[str, int, str, str]]],
|
|
650
|
+
file_text: str,
|
|
651
|
+
) -> _RefsOutcome:
|
|
652
|
+
"""Apply the proposals part by part, in order, to the text of the synthesis."""
|
|
653
|
+
outcomes = []
|
|
654
|
+
new_file = file_text
|
|
655
|
+
notes: dict[Path, tuple[bytes, bytes]] = {}
|
|
656
|
+
for name, items in by_part.items():
|
|
657
|
+
outcome = _refs_part_outcome(syn.sections, handle, root, name, items)
|
|
658
|
+
outcomes.append(outcome)
|
|
659
|
+
if outcome.change is not None:
|
|
660
|
+
new_file = synthesis_edit.apply_part_text(new_file, name, outcome.change[1])
|
|
661
|
+
notes.update(_refs_note_edits(root, handle, name, outcome.change))
|
|
662
|
+
return _RefsOutcome(
|
|
663
|
+
new_file,
|
|
664
|
+
notes,
|
|
665
|
+
[o.count_line for o in outcomes if o.count_line is not None],
|
|
666
|
+
[line for o in outcomes for line in o.refused],
|
|
667
|
+
sum(o.added for o in outcomes),
|
|
668
|
+
sum(o.removed for o in outcomes),
|
|
669
|
+
)
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _refs_write(
|
|
673
|
+
path: Path, original: bytes, outcome: _RefsOutcome, root: Path, today: datetime.date
|
|
674
|
+
) -> None:
|
|
675
|
+
"""Write the synthesis and the member notes as one logged group."""
|
|
676
|
+
changes = {
|
|
677
|
+
path: (original, synthesis_edit.bumped(outcome.new_file, today).encode("utf-8")),
|
|
678
|
+
**outcome.notes,
|
|
679
|
+
}
|
|
680
|
+
_synthesis_require_writable(changes)
|
|
681
|
+
_write_logged_changes(
|
|
682
|
+
changes, root / records.CURATION_LOG, lambda: _log_group_ahead(root, changes, "refs")
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _refs_run(args: argparse.Namespace, root: Path, today: datetime.date) -> _RefsRun:
|
|
687
|
+
"""Read the proposals, apply them and write the files; the lines are printed by the caller."""
|
|
688
|
+
target = _refs_target(args.target, root / document.SYNTHESES_DIR)
|
|
689
|
+
if target is None:
|
|
690
|
+
return _RefsRun(1, [], False)
|
|
691
|
+
handle, path = target
|
|
692
|
+
raw = _refs_read_file(args.file)
|
|
693
|
+
if raw is None:
|
|
694
|
+
return _RefsRun(1, [], False)
|
|
695
|
+
syn = document.load_one(path)
|
|
696
|
+
if syn.error:
|
|
697
|
+
raise ValueError(f"{path.name}: {syn.error}")
|
|
698
|
+
original = path.read_bytes()
|
|
699
|
+
file_text = original.decode("utf-8")
|
|
700
|
+
edit._lf(file_text, path.name)
|
|
701
|
+
by_part, malformed = _refs_proposals(raw)
|
|
702
|
+
if not (by_part or malformed):
|
|
703
|
+
print("mem: the file holds no proposal", file=sys.stderr)
|
|
704
|
+
return _RefsRun(1, [], False)
|
|
705
|
+
outcome = _refs_collect(syn, handle, root, by_part, file_text)
|
|
706
|
+
changed = bool(outcome.added or outcome.removed)
|
|
707
|
+
if changed:
|
|
708
|
+
_refs_write(path, original, outcome, root, today)
|
|
709
|
+
refused = [*malformed, *outcome.refused]
|
|
710
|
+
summary = (
|
|
711
|
+
f"s:{handle}: added {outcome.added}, removed {outcome.removed}, refused {len(refused)}"
|
|
712
|
+
)
|
|
713
|
+
return _RefsRun(0, [*outcome.counts, *refused, summary], changed)
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _refs(args: argparse.Namespace) -> int:
|
|
717
|
+
"""`mem synthesis refs s:<handle> --file F`: add or remove references by unit number and source target, never
|
|
718
|
+
by text. Every changed part, and each member note that stays current, is written as one logged group."""
|
|
719
|
+
root = args.root.resolve()
|
|
720
|
+
try:
|
|
721
|
+
run = _refs_run(args, root, datetime.date.today())
|
|
722
|
+
except (
|
|
723
|
+
common.NewNoteError,
|
|
724
|
+
OSError,
|
|
725
|
+
ValueError,
|
|
726
|
+
note_files.FrontmatterError,
|
|
727
|
+
yaml.YAMLError,
|
|
728
|
+
) as exc:
|
|
729
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
730
|
+
return 2
|
|
731
|
+
if run.code != 0:
|
|
732
|
+
return run.code
|
|
733
|
+
print("\n".join(run.lines))
|
|
734
|
+
if run.changed:
|
|
735
|
+
common.log_usage(root, {"cmd": "synthesis", "action": "refs"})
|
|
736
|
+
return 0
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _detached(text: str, rel: str) -> str:
|
|
740
|
+
"""The note's text without `part_of` and `part_of_hash`."""
|
|
741
|
+
return common._set_field(
|
|
742
|
+
common._set_field(edit._lf(text, rel), "part_of", None), "part_of_hash", None
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _renamed_part_of(text: str, rel: str, part_of: str) -> str:
|
|
747
|
+
"""The note's text with `part_of` set to `part_of`; `part_of_hash` stays, so a stale note stays listed."""
|
|
748
|
+
return common._set_field(edit._lf(text, rel), "part_of", part_of)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
@dataclass(frozen=True)
|
|
752
|
+
class _SectionNote:
|
|
753
|
+
"""The knowledge note that summarizes a section just added: its topics, origin, text and `part_of` link, and the
|
|
754
|
+
section text its fingerprint stands for."""
|
|
755
|
+
|
|
756
|
+
topics: list[str]
|
|
757
|
+
origin: str
|
|
758
|
+
body: str | None
|
|
759
|
+
part_of: str
|
|
760
|
+
cleaned: str
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _synthesis_note_origin(cleaned: str) -> str:
|
|
764
|
+
"""The origin of the note that summarizes a section, from the kinds of source the section cites."""
|
|
765
|
+
kinds = document.source_kinds(cleaned)
|
|
766
|
+
if kinds & {"literature", "url"}:
|
|
767
|
+
return "literature"
|
|
768
|
+
if "research" in kinds:
|
|
769
|
+
return "research"
|
|
770
|
+
return "experience" if "experience" in kinds else "literature"
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _synthesis_note_new(
|
|
774
|
+
args: argparse.Namespace, root: Path, note: _SectionNote, today: datetime.date
|
|
775
|
+
) -> tuple[Path, bool]:
|
|
776
|
+
"""Create the note; (its path, whether its domain folder is new)."""
|
|
777
|
+
known = note_files.load_topics(root)
|
|
778
|
+
domain = (
|
|
779
|
+
note_files.root_of(known, note.topics[0])
|
|
780
|
+
if note.topics and note.topics[0] in known
|
|
781
|
+
else None
|
|
782
|
+
)
|
|
783
|
+
created = not (root / "knowledge" / str(domain)).exists()
|
|
784
|
+
target = edit.new_note(
|
|
785
|
+
root,
|
|
786
|
+
"knowledge",
|
|
787
|
+
slug=args.note_slug,
|
|
788
|
+
topics=note.topics,
|
|
789
|
+
today=today,
|
|
790
|
+
body=note.body,
|
|
791
|
+
claim=args.note_claim,
|
|
792
|
+
confidence=args.confidence,
|
|
793
|
+
level=args.level,
|
|
794
|
+
origin=note.origin,
|
|
795
|
+
part_of=note.part_of,
|
|
796
|
+
part_of_hash=units.fingerprint(note.cleaned),
|
|
797
|
+
)
|
|
798
|
+
return target, created
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _synthesis_note_checked(root: Path, target: Path, cleaned: str) -> str:
|
|
802
|
+
"""Stamp the note's `part_of_hash` and require that it has no check problem; returns its path."""
|
|
803
|
+
rel = target.relative_to(root).as_posix()
|
|
804
|
+
if (stamp := units.note_fingerprint(cleaned, common._note_target(rel))) != units.fingerprint(
|
|
805
|
+
cleaned
|
|
806
|
+
):
|
|
807
|
+
safe_io.replace_file(
|
|
808
|
+
target,
|
|
809
|
+
common._set_field(note_files._read_text(target), "part_of_hash", stamp).encode("utf-8"),
|
|
810
|
+
)
|
|
811
|
+
if found := [p for p in check_rules.check(root) if p.path == rel]:
|
|
812
|
+
raise common.NewNoteError(
|
|
813
|
+
f"the note has {len(found)} problems, so nothing was written: "
|
|
814
|
+
+ "; ".join(str(p) for p in found)
|
|
815
|
+
)
|
|
816
|
+
return rel
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def _synthesis_note_discard(root: Path, target: Path, created: bool) -> None:
|
|
820
|
+
"""Remove the note of a failed add, with its domain folder when the add created it, and refresh the listings."""
|
|
821
|
+
target.unlink(missing_ok=True)
|
|
822
|
+
if created:
|
|
823
|
+
shutil.rmtree(target.parent, ignore_errors=True)
|
|
824
|
+
with contextlib.suppress(note_files.FrontmatterError, OSError):
|
|
825
|
+
index_files.apply_index(root)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _add_with_note(
|
|
829
|
+
args: argparse.Namespace, path: Path, handle: str, body: str, today: datetime.date
|
|
830
|
+
) -> str:
|
|
831
|
+
"""The section and the knowledge note that summarizes it, both or neither; returns the note's path."""
|
|
832
|
+
root = args.root
|
|
833
|
+
syn = document.load_one(path)
|
|
834
|
+
note_body = common._read_body(args.note_body_file)
|
|
835
|
+
section_handle, _, cleaned = synthesis_edit.prepare_add(path, args.section, body, today)
|
|
836
|
+
note = _SectionNote(
|
|
837
|
+
topics=list(syn.topics),
|
|
838
|
+
origin=args.origin or _synthesis_note_origin(cleaned),
|
|
839
|
+
body=note_body,
|
|
840
|
+
part_of=f"{handle}#{section_handle}",
|
|
841
|
+
cleaned=cleaned,
|
|
842
|
+
)
|
|
843
|
+
undo = synthesis_edit.snapshot(path)
|
|
844
|
+
synthesis_edit.add_section(path, args.section, body, today)
|
|
845
|
+
target = None
|
|
846
|
+
created = False
|
|
847
|
+
try:
|
|
848
|
+
target, created = _synthesis_note_new(args, root, note, today)
|
|
849
|
+
rel = _synthesis_note_checked(root, target, cleaned)
|
|
850
|
+
except Exception:
|
|
851
|
+
if target is not None:
|
|
852
|
+
_synthesis_note_discard(root, target, created)
|
|
853
|
+
undo()
|
|
854
|
+
raise
|
|
855
|
+
return rel
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _synthesis_list(args: argparse.Namespace) -> int:
|
|
859
|
+
"""`mem synthesis list`: one line per synthesis, those of `--topic` and its descendants only."""
|
|
860
|
+
listed = document.load(args.root / document.SYNTHESES_DIR)
|
|
861
|
+
try:
|
|
862
|
+
known = note_files.load_topics(args.root)
|
|
863
|
+
except note_files.FrontmatterError:
|
|
864
|
+
known = {}
|
|
865
|
+
wanted = {args.topic, *note_files.descendants(known, args.topic)} if args.topic else None
|
|
866
|
+
for syn in listed:
|
|
867
|
+
if syn.error:
|
|
868
|
+
print(f"mem: skipped {syn.path}: {syn.error}", file=sys.stderr)
|
|
869
|
+
elif wanted is None or wanted & set(syn.topics):
|
|
870
|
+
print(f"s:{syn.handle}\t{len(syn.parts)} parts, updated {syn.updated}\t{syn.title}")
|
|
871
|
+
return 0
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _synthesis_handlers() -> dict[str, Callable[[argparse.Namespace], int]]:
|
|
875
|
+
"""The subcommands that read or restructure; any other one writes a synthesis or one of its parts."""
|
|
876
|
+
return {
|
|
877
|
+
"list": _synthesis_list,
|
|
878
|
+
"attach": edit._attach,
|
|
879
|
+
"rename": _structure,
|
|
880
|
+
"remove": _structure,
|
|
881
|
+
"detach": _structure,
|
|
882
|
+
"topics": _structure,
|
|
883
|
+
"refs": _refs,
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _synthesis_one_call(args: argparse.Namespace, action: str) -> bool:
|
|
888
|
+
"""Whether `add` also writes the note that summarizes the section; the five options go together."""
|
|
889
|
+
note_group = (
|
|
890
|
+
[args.note_slug, args.note_claim, args.note_body_file, args.confidence, args.level]
|
|
891
|
+
if action == "add"
|
|
892
|
+
else []
|
|
893
|
+
)
|
|
894
|
+
one_call = any(note_group)
|
|
895
|
+
if one_call and not all(note_group):
|
|
896
|
+
raise common.UsageError(
|
|
897
|
+
"--note-slug, --note-claim, --note-body-file, --confidence and --level go together"
|
|
898
|
+
)
|
|
899
|
+
return one_call
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def _synthesis_new_topics(args: argparse.Namespace, root: Path) -> list[str]:
|
|
903
|
+
"""The topics of a new synthesis; ValueError when one is unknown, none is given or another synthesis covers one."""
|
|
904
|
+
topics = [t.strip() for t in args.topics.split(",") if t.strip()]
|
|
905
|
+
known = note_files.load_topics(root)
|
|
906
|
+
if not topics:
|
|
907
|
+
raise ValueError("at least one topic is required")
|
|
908
|
+
for t in topics:
|
|
909
|
+
if t not in known:
|
|
910
|
+
raise ValueError(f"unknown topic '{t}': use an id from topics.yaml or add it there")
|
|
911
|
+
for other in document.load(root / document.SYNTHESES_DIR):
|
|
912
|
+
if other.error is None and (clash := [t for t in topics if t in other.topics]):
|
|
913
|
+
raise ValueError(
|
|
914
|
+
f"s:{other.handle} already covers the topic {clash[0]}; add a part to it."
|
|
915
|
+
)
|
|
916
|
+
return topics
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def _synthesis_create(args: argparse.Namespace) -> int:
|
|
920
|
+
"""`mem synthesis new`: the file of a synthesis with its summary."""
|
|
921
|
+
root = args.root
|
|
922
|
+
topics = _synthesis_new_topics(args, root)
|
|
923
|
+
summary = _synthesis_text(args.summary_file)
|
|
924
|
+
if summary is None:
|
|
925
|
+
return 1
|
|
926
|
+
if common._refuse_secret([args.title, summary]):
|
|
927
|
+
return 4
|
|
928
|
+
approved = getattr(args, "owner_approved", False)
|
|
929
|
+
if refused := common._check_terms([args.title, args.slug, summary], "synthesis", approved):
|
|
930
|
+
return refused
|
|
931
|
+
text = synthesis_edit.render_new(
|
|
932
|
+
(common._TEMPLATES / "synthesis.md").read_text(encoding="utf-8"),
|
|
933
|
+
title=args.title,
|
|
934
|
+
topics=topics,
|
|
935
|
+
summary=summary,
|
|
936
|
+
today=datetime.date.today(),
|
|
937
|
+
)
|
|
938
|
+
path = synthesis_edit.create(root / document.SYNTHESES_DIR, args.slug, text)
|
|
939
|
+
print(f"s:{path.stem}\t{path.relative_to(root).as_posix()}")
|
|
940
|
+
return 0
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
@dataclass(frozen=True)
|
|
944
|
+
class _SynthesisWrite:
|
|
945
|
+
"""What a command that writes a part of a synthesis carries: the file, its handle, the part the reference names
|
|
946
|
+
(None for `add`), the text and whether `add` also writes a note."""
|
|
947
|
+
|
|
948
|
+
path: Path
|
|
949
|
+
handle: str
|
|
950
|
+
section: str | None
|
|
951
|
+
body: str
|
|
952
|
+
one_call: bool
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def _synthesis_note_texts(args: argparse.Namespace, one_call: bool) -> list[str] | None:
|
|
956
|
+
"""The claim and the text of the note an `add` also writes ([] when it writes none); None when the text is unreadable."""
|
|
957
|
+
if not one_call:
|
|
958
|
+
return []
|
|
959
|
+
note_body = _synthesis_text(args.note_body_file)
|
|
960
|
+
return None if note_body is None else [args.note_claim, note_body]
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def _synthesis_refused(args: argparse.Namespace, body: str, note_texts: list[str]) -> int:
|
|
964
|
+
"""0 when the texts may be written, else the exit code after a message on stderr."""
|
|
965
|
+
heading = getattr(args, "section", None) or ""
|
|
966
|
+
approved = getattr(args, "owner_approved", False)
|
|
967
|
+
if common._refuse_secret([heading, body, *note_texts]):
|
|
968
|
+
return 4
|
|
969
|
+
if refused := common._check_terms([heading, body], "synthesis", approved):
|
|
970
|
+
return refused
|
|
971
|
+
if note_texts:
|
|
972
|
+
return common._check_terms([*note_texts, args.note_slug], "note", approved)
|
|
973
|
+
return 0
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def _synthesis_require_valid_section(body: str, root: Path) -> None:
|
|
977
|
+
"""ValueError listing the problems of a section text; a blank text has none."""
|
|
978
|
+
problems = document.validate_section(body, root) if body.strip() else []
|
|
979
|
+
if problems:
|
|
980
|
+
raise ValueError("; ".join(problems))
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def _synthesis_section_of(args: argparse.Namespace, write: _SynthesisWrite) -> str:
|
|
984
|
+
"""The section the reference names; ValueError when `append` or `edit` got none."""
|
|
985
|
+
if write.section is None:
|
|
986
|
+
raise ValueError(f"{args.synthesis_command} takes s:<handle>#<section handle>")
|
|
987
|
+
return write.section
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def _synthesis_add(args: argparse.Namespace, write: _SynthesisWrite) -> str:
|
|
991
|
+
"""`mem synthesis add`: a new section, with its note in one call; returns the new section's handle."""
|
|
992
|
+
if write.section is not None:
|
|
993
|
+
raise ValueError("add takes s:<handle>, not a section")
|
|
994
|
+
_synthesis_require_valid_section(write.body, args.root)
|
|
995
|
+
today = datetime.date.today()
|
|
996
|
+
note_rel = ""
|
|
997
|
+
if write.one_call:
|
|
998
|
+
note_rel = _add_with_note(args, write.path, write.handle, write.body, today)
|
|
999
|
+
new_handle = document.section_handle(args.section)
|
|
1000
|
+
else:
|
|
1001
|
+
new_handle = synthesis_edit.add_section(write.path, args.section, write.body, today)
|
|
1002
|
+
print(f"s:{write.handle}#{new_handle}\tadded")
|
|
1003
|
+
if write.one_call:
|
|
1004
|
+
print(note_rel)
|
|
1005
|
+
return new_handle
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _synthesis_append(args: argparse.Namespace, write: _SynthesisWrite) -> str:
|
|
1009
|
+
"""`mem synthesis append`: text added to a section; returns the section's handle."""
|
|
1010
|
+
section = _synthesis_section_of(args, write)
|
|
1011
|
+
synthesis_edit.append_section(
|
|
1012
|
+
write.path, section, write.body, datetime.date.today(), store=args.root
|
|
1013
|
+
)
|
|
1014
|
+
print(f"s:{write.handle}#{section}\tappended")
|
|
1015
|
+
return section
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def _synthesis_edit(args: argparse.Namespace, write: _SynthesisWrite) -> str:
|
|
1019
|
+
"""`mem synthesis edit`: a section's text replaced; returns the section's handle."""
|
|
1020
|
+
section = _synthesis_section_of(args, write)
|
|
1021
|
+
if section != document.SUMMARY:
|
|
1022
|
+
_synthesis_require_valid_section(write.body, args.root)
|
|
1023
|
+
synthesis_edit.edit_section(
|
|
1024
|
+
write.path,
|
|
1025
|
+
section,
|
|
1026
|
+
write.body,
|
|
1027
|
+
datetime.date.today(),
|
|
1028
|
+
shrink=args.shrink,
|
|
1029
|
+
drop_references=args.drop_references,
|
|
1030
|
+
)
|
|
1031
|
+
print(f"s:{write.handle}#{section}\tedited")
|
|
1032
|
+
return section
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def _synthesis_part(args: argparse.Namespace, one_call: bool) -> int:
|
|
1036
|
+
"""`mem synthesis add | append | edit`: the text of one part, checked before anything is written."""
|
|
1037
|
+
ref = args.target
|
|
1038
|
+
handle, section = document.split_ref(ref)
|
|
1039
|
+
path = document.path_of(args.root / document.SYNTHESES_DIR, handle)
|
|
1040
|
+
if path is None or not path.is_file():
|
|
1041
|
+
raise ValueError(f"no synthesis named {ref}")
|
|
1042
|
+
body = _synthesis_text(args.body_file)
|
|
1043
|
+
note_texts = _synthesis_note_texts(args, one_call) if body is not None else None
|
|
1044
|
+
if body is None or note_texts is None:
|
|
1045
|
+
return 1
|
|
1046
|
+
if refused := _synthesis_refused(args, body, note_texts):
|
|
1047
|
+
return refused
|
|
1048
|
+
write = _SynthesisWrite(path, handle, section, body, one_call)
|
|
1049
|
+
writers = {"add": _synthesis_add, "append": _synthesis_append}
|
|
1050
|
+
shown = writers.get(args.synthesis_command, _synthesis_edit)(args, write)
|
|
1051
|
+
_long_note(handle, path, shown)
|
|
1052
|
+
return 0
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
def parser_links(synthesis_sub: Any) -> None:
|
|
1056
|
+
"""The `refs`, `topics` and `list` subcommands of `mem synthesis`."""
|
|
1057
|
+
syn_refs = synthesis_sub.add_parser(
|
|
1058
|
+
"refs", help="add or remove inline note references from a file of proposals"
|
|
1059
|
+
)
|
|
1060
|
+
syn_refs.add_argument("target", metavar="s:HANDLE")
|
|
1061
|
+
syn_refs.add_argument(
|
|
1062
|
+
"--file",
|
|
1063
|
+
required=True,
|
|
1064
|
+
metavar="PATH",
|
|
1065
|
+
help="one proposal per line: SECTION | UNIT | add TARGET or SECTION | UNIT | remove TARGET",
|
|
1066
|
+
)
|
|
1067
|
+
syn_topics = synthesis_sub.add_parser("topics", help="replace a synthesis's topics")
|
|
1068
|
+
syn_topics.add_argument("target", metavar="s:HANDLE")
|
|
1069
|
+
syn_topics.add_argument("topic_ids", metavar="TOPICS", help="comma-separated topic ids")
|
|
1070
|
+
syn_list = synthesis_sub.add_parser("list", help="one line per synthesis")
|
|
1071
|
+
syn_list.add_argument("--topic")
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
def cmd_synthesis(args: argparse.Namespace) -> int:
|
|
1075
|
+
handler = _synthesis_handlers().get(args.synthesis_command)
|
|
1076
|
+
if handler is not None:
|
|
1077
|
+
return handler(args)
|
|
1078
|
+
action = args.synthesis_command
|
|
1079
|
+
one_call = _synthesis_one_call(args, action)
|
|
1080
|
+
try:
|
|
1081
|
+
code = _synthesis_create(args) if action == "new" else _synthesis_part(args, one_call)
|
|
1082
|
+
except (
|
|
1083
|
+
ValueError,
|
|
1084
|
+
OSError,
|
|
1085
|
+
note_files.FrontmatterError,
|
|
1086
|
+
yaml.YAMLError,
|
|
1087
|
+
common.NewNoteError,
|
|
1088
|
+
) as exc:
|
|
1089
|
+
print(f"mem: {exc}", file=sys.stderr)
|
|
1090
|
+
return 1
|
|
1091
|
+
if code != 0:
|
|
1092
|
+
return code
|
|
1093
|
+
common.log_usage(args.root, {"cmd": "synthesis", "action": action})
|
|
1094
|
+
return 0
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def parser_sections(synthesis_sub: Any, owner_approved: str) -> None:
|
|
1098
|
+
syn_append = synthesis_sub.add_parser(
|
|
1099
|
+
"append", help="add text at the end of a section, before its Sources line"
|
|
1100
|
+
)
|
|
1101
|
+
syn_append.add_argument("target", metavar="s:HANDLE#SECTION")
|
|
1102
|
+
syn_append.add_argument(
|
|
1103
|
+
"--body-file", required=True, metavar="PATH", help="the text (or - for standard input)"
|
|
1104
|
+
)
|
|
1105
|
+
syn_attach = synthesis_sub.add_parser(
|
|
1106
|
+
"attach", help="make a knowledge note the short recall of a section"
|
|
1107
|
+
)
|
|
1108
|
+
syn_attach.add_argument("note", metavar="NOTE")
|
|
1109
|
+
syn_attach.add_argument("target", metavar="s:HANDLE#SECTION")
|
|
1110
|
+
syn_rename = synthesis_sub.add_parser(
|
|
1111
|
+
"rename", help="rename a section's heading; its notes follow"
|
|
1112
|
+
)
|
|
1113
|
+
syn_rename.add_argument("target", metavar="s:HANDLE#SECTION")
|
|
1114
|
+
syn_rename.add_argument("heading", metavar="NEW_HEADING")
|
|
1115
|
+
syn_remove = synthesis_sub.add_parser(
|
|
1116
|
+
"remove", help="take a section out; its notes lose part_of"
|
|
1117
|
+
)
|
|
1118
|
+
syn_remove.add_argument("target", metavar="s:HANDLE#SECTION")
|
|
1119
|
+
syn_detach = synthesis_sub.add_parser("detach", help="remove a note's part_of")
|
|
1120
|
+
syn_detach.add_argument("note", metavar="NOTE")
|
|
1121
|
+
syn_append.add_argument("--owner-approved", action="store_true", help=owner_approved)
|
|
1122
|
+
syn_rename.add_argument("--owner-approved", action="store_true", help=owner_approved)
|